1

I am trying to move four objects and a SteamVR player by updating the transform.position. This works fine, however it does not look so well because the movement is like instant. That is why I want to use Vector3.MoveTowards().

Somehow, the code below is not doing the job. I was hoping that someone could help me out.

    private void ZoomObject(Vector3 currentPlayerPosition, float height, float distance)
    {
        TPNorthObject.transform.position = Vector3.MoveTowards(TPNorthObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);
        TPEastObject.transform.position = Vector3.MoveTowards(TPEastObject.transform.position, new Vector3(distance, height, 0), 10 * Time.deltaTime);
        TPSouthObject.transform.position = Vector3.MoveTowards(TPSouthObject.transform.position, new Vector3(0, height, -distance), 10 * Time.deltaTime);
        TPWestObject.transform.position = Vector3.MoveTowards(TPWestObject.transform.position, new Vector3(-distance, height, 0), 10 * Time.deltaTime);
    }

What I expected was, that the object would float to the new vector place. However it does not seem to do that.

Can someone give me some insight or advice?

Thanks in advance

zerk
  • 516
  • 4
  • 9
  • 34

1 Answers1

2

From Unity's documentation:

https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

Calculate a position between the points specified by current and target, moving no farther than the distance specified by maxDistanceDelta.

Use the MoveTowards member to move an object at the current position toward the target position. By updating an object’s position each frame using the position calculated by this function, you can move it towards the target smoothly. Control the speed of movement with the maxDistanceDelta parameter.

That is to say that MoveTowards doesn't do the smooth animation for you. If you wan't some kind of animation effect, your ZoomObject function needs to be called in a loop until your object reaches the target position. Check out the example on the documentation page.

You can use a loop or a coroutine to do that. Maybe something that would look like this.

IEnumerator Fade() 
{

    while (Vector3.Distance(TPNorthObject.transform.position, new Vector3(0, height, distance)) > 0.001f)
    {
        // Speed = Distance / Time => Distance = speed * Time. => Adapt the speed if move is instant.
        TPNorthObject.transform.position = Vector3.MoveTowards(TPNorthObject.transform.position, new Vector3(0, height, distance), 10 * Time.deltaTime);

        yield return null;
    }
}
Pierre Baret
  • 1,773
  • 2
  • 17
  • 35