Preventing movement keys from cancelling each other?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sempiro

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)
:bust_in_silhouette: Reply From: Gabriel

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"))