The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes
extends KinematicBody2D

const Gravity = 5
var jumped = false
var speed = Vector2.ZERO
func _ready():

func physicsprocess(delta):

if Input.is_action_pressed("ui_right"):
    speed.x  += 6
    $AnimatedSprite.flip_h = false
elif Input.is_action_pressed("ui_left"):
    speed.x -= 6
    $AnimatedSprite.flip_h = true 
elif Input.is_action_just_pressed("ui_up"):
    speed.y += -20
    jumped = true
elif jumped == true:
    speed.y += Gravity
    jumped = false

    speed.x = 0


I have been trying to get the player to jump but the player flies up instead, what is causing this?
P.S: would also appreciate any critics on the code.

in Engine by (17 points)

1 Answer

0 votes
Best answer

It looks like the problem is that the gravity is only applied if no buttons are being pressed. Try applying the gravity every frame like this:
if not is_on_floor(): speed.y += gravity
The issue then is that speed.y will retain its value after landing, and will keep trying to fall. I would use moveandslide() instead of moveandcollide, because it returns the distance moved as a Vector2. set
speed = move_and_slide(speed, Vector2.UP)
(Vector2.UP is included to tell the physics engine which direction is up so it can check if it's on the floor)
Just make sure that when changing speed.x, you use "=" not "-=" or "+=" to make sure that your character moves at a constant speed.
I would do it like this.

if Input.is_action_pressed("ui_right"): speed.x = 6 $"Walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): speed.x = -6 $"Walk") $AnimatedSprite.flip_h = true if Input.is_action_just_pressed("ui_up"): speed.y -= 20
Then outside of the if,
speed.y += Gravity
Then finally
if speed.x == 0: $"Idle")
speed = move_and_slide(speed, Vector2.UP)
I didn't include speed.normalized() because 1, it returns the normalized value without actually setting speed equal to it, and 2, because that would only allow the player to move one unit per frame in whatever direction it's going.

by (130 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.