Search Unity

Vector3.MoveTowards how control speed?

Discussion in 'Getting Started' started by AlxLmu, Mar 16, 2018.

  1. AlxLmu

    AlxLmu

    Joined:
    Jul 18, 2017
    Posts:
    21
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    You can use Time.time, which starts at 0 at runtime and constantly increases by 1 per second as the game is running.
    So if you want an object to move for a specified amount of seconds, you could do something like this:
    Code (CSharp):
    1.  
    2. public class Thing : MonoBehavior {
    3.  
    4.    private float movementTime;
    5.  
    6.    void Start() {
    7.       movementTime = 0f;
    8.       MoveForSeconds(3f);
    9.    }
    10.  
    11.    void Update() {
    12.       if(Time.time < movementTime) {
    13.          transform.position = Vector3.MoveTowards(transform.position, target.position, Time.deltaTime);
    14.       }
    15.    }
    16.  
    17.    //Could be public if you want this method to be accessed by other scripts
    18.    void MoveForSeconds(float seconds) {
    19.       movementTime = Time.time + seconds;
    20.    }
    21. }
    22.  
     
    Ryiah and DerrickMoore like this.
  3. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
    Also, 'speed' in the API example is essentially UnitsMovedPerSecond.
     
    Ryiah and JoeStrout like this.
  4. AlxLmu

    AlxLmu

    Joined:
    Jul 18, 2017
    Posts:
    21
    Thank you both. speed = UnitsMovedPerSecond is a good advice

    When I count the number of update cycles per second I get to 33. In the window stats it says 41 fps. Why the difference?
     
  5. DocJ

    DocJ

    Joined:
    Dec 9, 2016
    Posts:
    98
    I’m very new to programming, but I’m currently working on a game where an object moves from a current position to a final position in a set amount of time and I’ve had good success using a function called SmoothDamp. This might be something that’s useful for you too. I think it’s similar to Time.time, not completely sure though.
    Anyway, I hope that helps.