- Home /
If (Moving on the negative X axis)???
like the title suggests how do I create an if statement that returns true if my gameObject is moving in the negative x axis.
Negative x axis is relative. Rather give a broader descrition of what you are trying to do and add code.
I am trying to flip a sprite when they move to the left towards negative x but all the if statements i make don't work. I have tried rigidbody.velocity and comparing current position with an old position but to no avail. @Cornelis-de-Jager
Answer by BastianUrbach · Sep 04, 2019 at 06:19 AM
If you're talking about Physics velocity, then it's pretty simple:
if (GetComponent<Rigidbody>().velocity.x < 0)
If you want to react to any kind of motion then it's a bit more difficult because outside of the physics engine, there isn't really "motion", you just "teleport" things in small steps. It's still possible though but you need to remember where the object was in the last frame to calculate its velocity:
Vector3 lastFramePosition; void Update() { var delta = transform.position - lastFramePosition; if (delta.x < 0) { // do something } lastFramePosition = transform.position; }
Answer by Cornelis-de-Jager · Sep 04, 2019 at 01:56 AM
Here is a function you can call to check if you are moving along negative axis. Note this only works if you are using Key A | D or Left Arrow | Right Arrow
bool IsPositive () => Input.GetAxis("Horizontal") > 0;
Your answer
![](https://koobas.hobune.stream/wayback/20220612211637im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
rigidbody.velocity not working on x axis 2 Answers
Need help with C# code. both gameObject and col.gameObject are getting destroyed. here is the code. 2 Answers
Destroy declaration but not game object 2 Answers
instantiate a gameobject or rigidbody? 1 Answer
Change Movespeed based on Mouse Input 0 Answers