Change direction after the body walked X distance

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

Hello guys, how are u all doing?

I’m trying to change a KinematicsBody2D direction when it moves an X direction from it’s initial position. I’m trying to use this code but it’s not working and I don’t have idea why.

func _physics_process(delta):
	walk()
	move_and_slide(motion, UP)
	
func walk():
	var initialX = initial_position.x
	var mxMove = max_move_distance
	var posX = self.position.x
	
	print("initialX ", initialX) #1318.27002
	print("mxMOve ", mxMove) #400
	print("posX ", posX) #It's updating fine
	print("trigger ", initialX - mxMove) #918.27002
	
	if posX == initialX - mxMove or posX == initialX + mxMove:
		motion.x = speed * -1
	else:
		motion.x = speed

It never triggers the if statment, even if the condition is true.
While writing this I though what may be the problem: the speed changes to speed * -1 for the one ms that the body is in that given position. Might be that?

Could you share the project? Have you tried checking >= or <= instead ==? I don’t know how you handle movement, but may be == is not being met.

p7f | 2019-01-16 13:18

Sure, I will send you the project
but I can only do that later, about 11h from now (I’m not home right now).

fpicoral | 2019-01-16 13:24

No problem! just post it here and i’ll try to help!

p7f | 2019-01-16 13:25

I’d say it could be caused by two things:

  • You are checking perfect equality, however with float numbers this often doesn’t work because there can be float imprecision. Even print functions can miss this because they might round decimals.
  • Because the body moves by an amount dependent on physics step time (motion may be in pixels per second), there will always be decimals and there won’t be a frame where X becomes exactly equal to initialX. It will be slightly before, or slightly after. So it is recommended to use > or < depending on which direction you are going.

Zylann | 2019-01-16 13:53

Yes, i thought that too, and that’s why i asked if he tryed >= and <=

p7f | 2019-01-16 13:56

Yeah, I tried the other option (<= and >=) and now its working fine! Thanks!

fpicoral | 2019-01-17 00:14

Ok, glad that it worked! i’ll post it as an answer so the question does not remain unsolved.

p7f | 2019-01-17 00:29

:bust_in_silhouette: Reply From: p7f

As i said in comments, you should do >= or <= instead ==, because in float operations equality condition may not be met.