0 votes

just to ask. rather than post in the forum just now, because i think that this can be updated better.

but doing a simple 4 button movement, up, down , left , right seems to be not working and dont know why. its odd.

tried this type of code in other platforms and its fine.

it works with the last movement code, so left/right is fine, but up/down, nope. not working

here is my code

func _fixed_process(delta):
LEFT_BTN = Input.is_action_pressed('LEFT_BTN');
RIGHT_BTN = Input.is_action_pressed('RIGHT_BTN');
UP_BTN = Input.is_action_pressed('UP_BTN');
DOWN_BTN = Input.is_action_pressed('DOWN_BTN');

if UP_BTN:
    self.set_linear_velocity(Vector2(0, -player_speed));
elif DOWN_BTN:
    self.set_linear_velocity(Vector2(0, player_speed));
else:
    self.set_linear_velocity(Vector2(0, 0));

if LEFT_BTN:
    self.set_linear_velocity(Vector2(-player_speed, 0));
elif RIGHT_BTN:
    self.set_linear_velocity(Vector2(player_speed, 0));
else:
    self.set_linear_velocity(Vector2(0, 0));
in Engine by (22 points)
edited by

1 Answer

+1 vote
Best answer

It's because the left and right code is overwriting the up and down code. You should use one Vector2 to set all of the movement, then set the linear velocity only once. Also the vector should be normalized so that diagonal movement is the same speed as horizontal and vertical movement.

func _fixed_process(delta):
    var LEFT_BTN = Input.is_action_pressed('LEFT_BTN');
    var RIGHT_BTN = Input.is_action_pressed('RIGHT_BTN');
    var UP_BTN = Input.is_action_pressed('UP_BTN');
    var DOWN_BTN = Input.is_action_pressed('DOWN_BTN');

    var movement = Vector2(0, 0)

    if UP_BTN:
        movement.y = -1;
    elif DOWN_BTN:
        movement.y = 1;

    if LEFT_BTN:
        movement.x = -1;
    elif RIGHT_BTN:
        movement.x = 1;

    movement = movement.normalized() * player_speed; #normalize movement

    self.set_linear_velocity(movement);
by (665 points)
selected by

thank you very much.
makes sense when i look at it more and more.
bookmarked just in case ;)

coming back to godot has been a little confusing, but happy to be back ;)

again, thanks

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 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 webmaster@godotengine.org with your username.