I'm trying to smoothly move an object from point a to point b:
Instantiate(cat, OffScreenLeft(), Quaternion.identity);
Debug.Log("start position: " + OffScreenLeft());
Debug.Log("end position: " + InPosition());
StartCoroutine(MoveFromTo(cat.transform, OffScreenLeft(), InPosition(), 3f));
IEnumerator MoveFromTo(Transform objectToMove, Vector3 a, Vector3 b, float speed) {
float step = (speed / (a - b).magnitude) * Time.fixedDeltaTime;
float t = 0;
while (t <= 1.0f) {
t += step; // Goes from 0 to 1, incrementing by step each time
objectToMove.position = Vector3.Lerp(a, b, t); // Move objectToMove closer to b
yield return new WaitForFixedUpdate();
}
objectToMove.position = b;
Debug.Log("move complete cat: " + cat.transform.position);
}
Here's the debug output:
start position: (-20.34, 4.33)
end position: (-8.67, 4.33)
move complete cat: (-8.67, 4.33, 0.00)
The debug output shows that the cat should have moved. But it still appears off screen left in its original position. What am I missing?
You instantiate a new object in the first line. Instantiation is kind of coping object and placing it to the scene. So, you create a copy of cat
and place it to the scene. But after this you continue work with cat
object. So you are changing the original cat
object(prefab or something) instead of created one.
You have to use the object, that you receive as a return value from Instantiate
method and continue your manipulations with it.