Search Unity

Resolved How to continue movement beyond a given vector (Overshoot)

Discussion in 'Scripting' started by Realspawn1, Sep 26, 2022.

  1. Realspawn1

    Realspawn1

    Joined:
    Jun 8, 2015
    Posts:
    128
    So i have this object moving to a vector3. How can i make it say overshoot it so it will keep moving in the same line(direction) but past this vector. here is what i Use.

    Code (CSharp):
    1.   transform.position = Vector3.MoveTowards(transform.position, target, speed*Time.deltaTime);
    Thank you for your time.
     
  2. mopthrow

    mopthrow

    Joined:
    May 8, 2020
    Posts:
    348
    Hi, you'd want to get a direction, then you can move in that direction using transform.Translate. At least that's one way.

    direction = target position - current position.

    Here's one that starts at the object's position, moves it towards world 0,0,0 and keeps going in the same direction.

    edit: Should probably normalize it too, which I forgot in the code below.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class MoveTheThing : MonoBehaviour
    4. {
    5.     public Vector3 direction;
    6.  
    7.     void Start()
    8.     {
    9.         Vector3 start = transform.position;
    10.         Vector3 target = new Vector3(0, 0, 0);
    11.         direction = (target - start);
    12.     }
    13.  
    14.     void Update()
    15.     {
    16.         transform.Translate(direction * Time.deltaTime);
    17.     }
    18. }
     
    Last edited: Sep 26, 2022
  3. Realspawn1

    Realspawn1

    Joined:
    Jun 8, 2015
    Posts:
    128

    that was it :) Thank you some times the littlest things can drive me crazy to figure it out :) Lesson learned
     
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,113
    yep, you should
    Code (csharp):
    1. direction = (target - start).normalized;
     
  5. Realspawn1

    Realspawn1

    Joined:
    Jun 8, 2015
    Posts:
    128
    Somehow it is off the exact point and moves in a straight line but not getting over the exact Vertor3 any ideas why ?
     
  6. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Are you comparing two Vector3 for equality? Like
    Code (CSharp):
    1. Vector3 targetPosition;
    2. if(transform.position == targetPosition)
    3. {
    4. Debug.Log("hit")
    5. }
    This will likely never work. Vector3 contain 3 float variables. Floats are imprecise.
    You need to test if it is close enough instead.
    Code (CSharp):
    1. if(Vector3.Distance(transform.position, targetPosition) < 0.01f)