- Home /
Why when comparing two gameobjects positions it's never true ?
void LateUpdate()
{
transform.position = Vector3.SmoothDamp(transform.position, target[targetIndex].position, ref velocity, smoothTime);
if (transform.position == target[targetIndex].position)
targetIndex++;
if (targetIndex == target.Length)
targetIndex = 0;
}
I used a break point and checked over and over again the values in transform.position and the target position are the same but it's not getting to the next line to the targetIndex ++;
Answer by Eno-Khaon · May 18, 2017 at 04:31 AM
When comparing floating point numbers (in this case, three of them in a Vector3), it's often quite likely that the values aren't 100% identical.
For float values, you can use Mathf.Approximately() to compare them with a safety net for floating point inaccuracy.
You can take a fairly simple approach for Vector3 values, though.
// This is unlikely to be true.
if (transform.position == target[targetIndex].position)
// This is much more likely to be true once you're close enough.
// Just set the threshold to whatever works best for results virtually indistinguishable from perfect.
if((transform.position - target[targetindex].position).sqrMagnitude < thresholdSquared)
The thresholdSquared value would be defined based on:
public float threshold; // For example, 0.01f
private float thresholdSquared;
void Start()
{
thresholdSquared = threshold * threshold;
}
Your answer
Follow this Question
Related Questions
Why when creating new animator controller for the character the character is not walking right ? 0 Answers
How can i Instantiate on the terrain from left to right ? 0 Answers
Why the tile map scripts take almost all the cpu usage ? cpu usage is getting to 99% at times 1 Answer
How can i rotate object by pressing on key R and keep object facing to me my self ? 0 Answers
How can i spawn new gameobjects to be inside the terrain area ? 2 Answers