Remove input priority, alternative

Another way of removing the input priority is to set the motion to 0 at the start, then add or subtract the SPEED from motion.x. This means that when both keys are pressed, the speed is both added to 0, and then subtracted, bringing it back to 0.

func _physics_process(delta):
	motion = Vector2()
	
	if Input.is_action_pressed("right"):
		motion.x += SPEED
	if Input.is_action_pressed("left"):
		motion.x -= SPEED
	
	move_and_slide(motion)
3 Likes

That’s how I did it in my code. I had seen it before, but Nathan Lovato (GDQuest) includes it in a lot of his videos.

I assume Yan will use the motion variable in other parts of the code so he probably intentionally created it outside of the _physics_process function. I did mine slightly differently so that the motion variable stayed outside:

# processes the physics engine every frame
func _physics_process(delta):
	# get input and set movement
	motion.x = 0
	if Input.is_action_pressed("ui_right"):
		motion.x += SPEED
	if Input.is_action_pressed("ui_left"):
		motion.x += -SPEED
	
	# apply movement to the player
	move_and_slide(motion)
1 Like

I have created the motion variable outside the _physics_process()
(note, there is no var there)

motion = Vector2() is simply resetting both the x and y to 0. Later, when jumping and falling is introduced, I change it to motion.x = 0 the same as you have

Yup, setting it to 0 and then adding/subtracting speed was my solution too. :slight_smile:

You can do the same with on line of code:

extends KinematicBody2D

var direction = Vector2()
var speed = 750

func _physics_process(delta):
	direction.x = int(Input.is_action_pressed("ui_right")) - int(Input.is_action_pressed("ui_left"))
	move_and_slide(direction * speed)

Privacy & Terms