Here’s the brief version: I have a distance variable in my update function that finds the distance between the transform.position and the transform.position of another object. The variable starts at the actual distance between the two objects, but then, for some indiscernible reason, immediately proceeds to increase at a rate proportional to the gametime passing.
The details: I have a target variable of type Transform and a distance variable of type float in a script attached to an object. The only time the distance variable is changed is in this code right here, from my Update function:
distanceToTarget = Vector3.Distance(Target.position,transform.position);
When it didn’t work, I set up a Gizmo to show the distance variable onscreen. What I saw was the distance variable rapidly alternating between the current distance and a steadily increasing value that had nothing to do with the distance. I’ve also tried to find the distance in different ways.
distanceToTarget = (Target.position - transform.position).magnitude;
This code had the exact same effect as the Vector3.Distance function.
distanceToTarget = Mathf.abs(Target.position.x - transform.position.x);
This code, on the other hand, worked perfectly, so I know it’s not the individual values within the objects’ Transforms. I still want to get a Vector3 distance, though, but I don’t know what’s wrong. If anyone has an answer, please tell me.
Edit:
After doing more tests, I have confirmed that Vector3.Distance is not the problem, but what I found is still confusing me. When I tried this code:
distanceToTarget = Mathf.abs(Target.position.y - transform.position.y);
I got the exact same problem, so I guess the problem is with my objects’ y positions. However, I can’t figure out why this happens. Neither object is actually moving along the y axis. The only thing that affects their y positions is gravity, but that shouldn’t matter if their actual position isn’t changing, right?