Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Move towards without stopping at the target location

Discussion in 'Scripting' started by ACrimson, Mar 28, 2017.

  1. ACrimson

    ACrimson

    Joined:
    Mar 28, 2017
    Posts:
    30
    I want to make an object moves to a target , but to keep it moving (in the same direction of course) after it reaches the target.
    I tried moveToward but it just stop when it reach the target..
     
    Berkeaksoy likes this.
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    You'll want to store the direction it's moving, and then use that. Subtract the positions to get the direction. To keep your speed constant, normalize the direction vector (make it have a length of 1).

    Let's say that you are moving towards "target":
    Code (csharp):
    1.  
    2. public Transform target;
    3. private Vector3 movementVector = Vector3.zero;
    4. public float moveSpeed = 1f; //units per second
    5.  
    6. void Start() { // or whatever function triggers the movement
    7. movementVector = (target.position - transform.position).normalized * moveSpeed;
    8. }
    9.  
    10. void Update() {
    11. transform.position += movementVector * time.deltaTime;
    12. }
     
  3. ACrimson

    ACrimson

    Joined:
    Mar 28, 2017
    Posts:
    30
    Thanks !
     
  4. Resme

    Resme

    Joined:
    May 2, 2017
    Posts:
    1
    You are a legend, been searching for 3 days!
     
  5. HyperBeeCore

    HyperBeeCore

    Joined:
    Oct 13, 2013
    Posts:
    11
    Sorry for the necropost -- but how would I do this if I only had the seconds per unit, and not the units per second?
     
  6. Cannist

    Cannist

    Joined:
    Mar 31, 2020
    Posts:
    64
    Code (CSharp):
    1. float unitsPerSecond = 1f / secondsPerUnit;
    Or you can just divide instead of multiplying.