-2

I am trying to make a character move a certain distance then change direction when they travel a certain distance... the logic here in my code might be wrong I still have to work on that that's not the issue, the problem is my if statement doesn't execute

public class EnemyControl : MonoBehaviour
{
    private int xMoveDirection=-1;
    private float x;
    void Start()
    {
        x=gameObject.transform.position.x;
    }
    void Update()
    {
        gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(xMoveDirection,0);
        if(x==0.00){
          Debug.Log("helloimhere");
          xMoveDirection=0;
          x=x+1;
        }
  • Does this answer your question? [Choosing an Epsilon Value for Floating Point Comparisons](https://stackoverflow.com/questions/46652980/choosing-an-epsilon-value-for-floating-point-comparisons) – Tanveer Badar Apr 20 '20 at 15:26
  • What *is* the value of `x` at that point? Can you add something like `Debug.Log($"x = {x}")` just before the "if"? – Hans Kesting Apr 20 '20 at 15:27
  • @DougDawson the value of x prior to the if statement by Debug shows as 4.13 – Aniket Vishwakarma Apr 20 '20 at 15:31
  • 4
    But if you are saying that `x` is `4.13` then why would you expect the `if` statement to execute? – Sean Apr 20 '20 at 15:43

1 Answers1

6

Any direct comparisons against floating point values will most likely fail, you're better off defining a range of values that are "close enough", for example Math.Abs(x) < 0.0001.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • I tried this, it still doesn't run the if statement – Aniket Vishwakarma Apr 20 '20 at 15:28
  • Related SO Question: https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre – Doug Dawson Apr 20 '20 at 15:29
  • You should rather use `if(x <= 0)` since it is extremely unlikely that even with defining a range the object is positioned exactly within this range at a certain frame ... you are probably overshooting! – derHugo Apr 21 '20 at 07:39