Unusual Bug

Just to mention, I’ve been trying to find out what has been causing this for 5 hours now. I think some other minds will help.

I am making an endless runner, where the runner is standing in one spot and the background scrolls behind him. I’m just changing the Y direction whenever the user clicks the mouse button. Whenever the player is at a certain Y location, he stops falling. If he is on that Y location he is able to click to flip and go back the other way. The player starts on -0.49 and works when I click the button. But when hes at 0.44 and I try clicking, it doesnt switch directions and keeps the runner there. It should switch directions. Help!:frowning:

Guitext test is just a bug test object disregard that.

using UnityEngine;
using System.Collections;

public class Physics : MonoBehaviour {

    sbyte direction = 1;
    public float gravity;
    Vector3 pos;
    public GUIText test;
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            if (pos.y <= -0.49)
            {
                direction *= -1;
            }
            if (pos.y >= 0.44)
            {
                direction *= -1;
            }
        }
        pos = transform.position;
        pos.y += (gravity * direction);
        test.text = pos.y.ToString();
        if (pos.y <= -0.49)
        {
            pos.y = -0.49f;
        }
        if (pos.y >= 0.44)
        {
            pos.y = 0.44f;
        }
        transform.position = pos;
    }
}

Probably a bit of floating point magic going on - stick an ‘f’ on the values in your if statements and see if that helps.

1 Like

Thank you! Hate those rounding errors.

1 Like

Interesting stuff:
http://babbage.cs.qc.edu/IEEE-754/

0.44 rounds to the following significand:
1.7599999904632568359375 for 32 bits (float)
1.7600000000000000088817841970012523233890 for 64 bits (double)

Since C# defaults to using doubles, the problem if statement would look (something) like this:
if (1.7599999904632568359375 >= 1.7600000000000000088817841970012523233890)

Which is obviously never true…

1 Like