I’m trying to move object A to object B until their positions match. But unfortunately object A never reaches the exact position of object B, it just gets really close (like x position is 7,9999999 where it should be 8). This is the code:
if (gameObject.transform.position == targetPosition)
{
//Do some stuff
}
else
{ gameObject.transform.Translate((targetPosition - gameObject.transform.position) * Time.deltaTime);
}
Any suggestion on how to solve that problem? Thanks in advance,
The problem is that, when you’re comparing these two things, they have to be exactly equal; if the two variables aren’t exact, then it will cause the object to keep moving.
EDIT: In other words, maybe you should create a trigger where the end point is, and on collision stop?
I just realized that Mattimus’ solution won’t work, as I cant use > or < with Vector3 variables. Any other ideas, that won’t need the use of colliders?
EDIT: Oddly, Mattimus post has disappeared. :?: [/code]
Your problem is that your code doesn’t move something to targetPosition. Instead, you’re moving by a fraction of how far you need to go, by multiplying the distance delta by Time.deltaTime. Unless you’re only achieving one frame per second or less, you’ll never get there. And if your game runs so terribly that you do in fact get less than 1 FPS, you’ll overshoot the target. I don’t know if you actually like the easing out that you get from your code. If it doesn’t matter to you, and linear motion is fine, then this code works. If you need easing, you can modify it slightly, using something like this.
Additionally, you don’t need to type gameObject.transform. transform, by itself, means the same thing.
var duration : float;
function MoveIt ()
{
var startPosition = transform.position;
var elapsedTime : float = 0;
while (elapsedTime < duration)
{
transform.position = Vector3.Lerp(startPosition, targetPosition, elapsedTime);
elapsedTime += Time.deltaTime;
Debug.Log(elapsedTime);
yield;
}
transform.position = targetPosition;
// Put code here that you want executed when the thing gets to targetPosition.
}
Thanks, especially Jessy! I really should have paid more attention at school on the topic vectors, and also not simply copied the move code from a tutorial without trying to understand it. I will try to implement it tomorrow, for today it’s time to relax =).
Thanks again for your help, it’s really appreciated.