0 votes

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?

in Engine by (521 points)

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.

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

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

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.

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

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

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

1 Answer

0 votes
Best answer

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

by (3,461 points)
selected by
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 Frequently asked questions and 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 [email protected] with your username.