Remove input priority, alternative

gdt_s03_physicsbody2d__making_a_character

#1

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)

#2

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.


#3

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)

#4

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


#5

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