0 votes

I want to stop two opposite keys from cancelling each other when they get pressed at the same time. For example if I press up, then down without releasing the up key the player goes down instead of freezing in place. My code:

extends KinematicBody2D

func _ready():
    pass

var MOVE_SPEED = 300

func _physics_process(delta):
    var move_vec = Vector2()
    if Input.is_action_pressed("ui_up"):
        move_vec.y -= 1
    if Input.is_action_pressed("ui_down"):
        move_vec.y += 1
    if Input.is_action_pressed("ui_left"):
        move_vec.x -= 1
    if Input.is_action_pressed("ui_right"):
        move_vec.x += 1
    move_vec = move_vec.normalized()
    move_and_collide(move_vec * MOVE_SPEED * delta)
in Engine by (14 points)

1 Answer

+2 votes

The problem is that each frame you are adding or subtracting 1 from move_vec.
Instead of using:

 move_vec.y -= 1
 move_vec.y += 1
 move_vec.x -= 1
 move_vec.x += 1

Try this:

move_vec.y = -1
move_vec.y = 1
move_vec.x = -1
move_vec.x = 1

Also you could use this:

move_vec.x = int(Input.is_action_pressed("ui_right")) - int(Input.is_action_pressed("ui_left"))
move_vec.y = int(Input.is_action_pressed("ui_up")) - int(Input.is_action_pressed("ui_down"))
by (247 points)
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.