0

i am trying to move an object up for 60 frames and then move it down for 60 frames, so it should go back to its original place. However, when i tried to do that, thats not what happened. the initial position of the object was (0,1.2,0) and after i moved it up and down, it backed to the position of (0,1.200001,0). This is the script that i wrote for the object.the object is a 3d cube with a box collider.

private float upCounter = 60; private float downCounter = 60; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (upCounter > 0) { transform.position += new Vector3(0, 0.5f, 0); } else { if (downCounter > 0) { transform.position -= new Vector3(0, 0.5f, 0); } downCounter--; } upCounter--; } 

Its important for my project that those position will be precised. How can i solve it? Thanks the helpers anyway.

2
  • Unity represents vectors using floating point numbers. Floats by themselves can't always make exact calculations due to how binary can't represent certain values with complete precision. You need to re-design your project so that it doesn't require that the float values be exactly equal. Why do they need to be exactly equal now? Commented May 23, 2019 at 19:28
  • 2
    Possible duplicate of Do Not Check Floating Point Equality/Inequality Commented May 23, 2019 at 19:35

1 Answer 1

2

Unity uses floats in its vectors. If your design requires that you compare floats exactly, you need to change your design.

Instead of testing if two floats are exactly equal, use Mathf.Approximately(f1,f2)

This checks if they are approximately equal accounting for floating point imprecision.

If you need to compare two Vector3, such as positions, are equal after manipulating them, use vector1 == vector2

When you do this, Unity will use Approximately on each component to test if they are approximately equal.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.