what do I miss with MoveTowards?

Hey all,
here is the situation:
I have one Main Camera, and 3 Dummy Camera’s which are only used to for it’s transform. now my goal is to change my Main Camera’s transform to the one of the selected Dummy Camera (by pressing 1, 2 or 3). the Main Camera moves for one frame into the right direction, but stops immediately , as if it will only move for one frame. On first glance I thought it happened because the next frame " i " was set to 0 the next frame, posibly meaning he forgets his target position, but even when I push the value of " i " over to targetCam in my MoveCamera function, it still doesn’t work.

So do I miss something, or do I simply misunderstand the MoveTowards function?
P.S, I rather like to have an explanation of how stuff works, instead of someone telling me the answer straight away. Otherwise I still have no clue what I did wrong hehe.

Cheers!

using UnityEngine;
using System.Collections;

public class MoveCameraTo : MonoBehaviour {

    public GameObject[] cameras;
    public string[] shortcuts;
    public float speed = 5;

    void Update () {
        for (int i = 0; i < cameras.Length; i++){
            if(Input.GetKeyDown(shortcuts[i])){
                MoveCamera(i);
            }
        }
    }

    void MoveCamera (int index){
        Debug.Log (index + " was pressed");
        int targetCam = index;
        transform.position = Vector3.MoveTowards(transform.position, cameras[targetCam].transform.position, speed*Time.deltaTime);
    }
}

GetKeyDown is only true for the single frame that the key is pressed down, so you only call the MoveCamera function once. You need to call MoveTowards every frame if you want it to work.

–Eric

1 Like

That I understand, but I thought that once you pressed a key, MoveTowards will move an object until it reaches it’s destination. How should I build the code that if you press the key once, it will move the camera all the way to it’s new position?

No, MoveTowards, like other functions such as Lerp, doesn’t “do stuff over time” or anything. It returns a value once, immediately. As I mentioned, you need to call it repeatedly in Update (or a coroutine).

–Eric

1 Like

so if i am correct (i’m just trying to understand the way all functions work), it goes something like …

Vector3.MoveTowards(A, B, C)

if the current position of whatever object this script is attached to hasn’t reached position B yet, it will calculate how much the object has moved between point A and B at a certain speed (C) after one frame.

Pretty much, except C is technically a distance, not speed.

–Eric

1 Like

thank you very much!