1
    if (((float) (Math.Round(gameObject.transform.position.x, 1))) == ((float) (Math.Round(array[i].x, 1))) && (((float) (Math.Round(gameObject.transform.position.y, 1))) ==  (float) (Math.Round(array[i].y, 1))))

Hello! I am using C#, and the array is filled with vector positions. I am trying to see when an object gets to a certain position. This never triggers. Do you have any other tips how to do this?

dudeperryfect
  • 1,787
  • 2
  • 7
  • 6
  • It wont work because of precision. You can take a look at this [question](https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp) for how to achieve what you want. – Ali Kanat Mar 14 '19 at 10:23

1 Answers1

3

You are comparing float values directly ... never do that. It leads to a problem with the floating point precision. float values are internally actually stored in increments of an Epsilon.

see e.g. from here

The nearest float to 16.67 is 16.6700000762939453125

The nearest float to 100.02 is 100.01999664306640625

or here for a broader explenation.


Use Vector3.Distance!

Preferably with a certain threshold distance. There is an example that looks exactly like what you want to do in Coroutines (in JavaScript but the difference to c# in this case is minimal)

public float threshold = 0.1f;

//...

if(Vector3.Distance(gameObject.transform.position, array[i]) <= threshold)
{
    ....
}

Adjust threshold so it has a value that is bigger than what the object can possibly move between two frames.

Or together with Mathf.Approximately

if(Math.Approximately(Vector3.Distance(object.transform.position, array[i]), 0.0f))
{
    ....
}

if your threshold is smaller than 0.00001 than you could also use

if(object.transform.position == array[i])
{
    ....
}

since == uses <= 0.00001 for equality.

But note: In the most cases the last two options will also fail because the opts for a moving GameObject to match an exact 3D position are almost 0 unless you set fixed values somewhere.


Vector3.Distance also works with a Vector2 as parameter since an implicit typecast to Vector3 exists.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Thanks! Do you know why my program crashes when i i wrap that if statement with: while(x==1) { if statement with x=0; – dudeperryfect Mar 14 '19 at 11:00
  • most probably because you don't ever move your object insdie the while loop or it simply never matches the position for any other reason? Do your check only in `Update` without a `while` .. `Update` si called every frame that should be enough. Or checkout [Coroutines](https://docs.unity3d.com/Manual/Coroutines.html) (just noticed there is actually exactly the example I provided above using `Distance` ;) ) – derHugo Mar 14 '19 at 11:06