Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Move an object towards a target position, using the current objects Vector3s offset as the target?

Discussion in 'Scripting' started by MachineHead, Aug 22, 2021.

  1. MachineHead

    MachineHead

    Joined:
    Jan 6, 2016
    Posts:
    30
    Using Vector3.MoveTowards, you can move a current objects position to a target position. Usually, for me, either an empty game objects transform, or the player game object transform.

    How can I do it without having an empty game object or player to target, but use the current objects position, and calculate its offset in a particular angle to be its target vector?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,522
    You mean, "I am here, I want you to go northeast 10 meters?"

    If position A is here

    If heading H is heading in degrees

    If distance D is how far away in meters

    Then target position T is given by:

    Code (csharp):
    1. Vector3 A = where I am now
    2. float H = heading in degrees around compass
    3. float D = distance away from me
    4.  
    5. // where I want you to go:
    6. Vector3 T = A + Quaternion.Euler( 0, H, 0) * Vector3.forward * D;
    Assuming that heading 0 is north (the .forward part).
     
  3. MachineHead

    MachineHead

    Joined:
    Jan 6, 2016
    Posts:
    30
    Yes, that's what I'm talking about. Also, Quaternion.Euler is what I was missing.
    I'm spawning projectiles on an automatic rotating turret that isn't exactly targeting the player, but filling the screen. I theorize the next roadblock I'm going to hit is as the spawn point rotates, Vector3 A, the euler, H, will have to change its degrees. Say current position is facing north, then H will be +20, but when the current position is facing south, it needs to be -20. I think that may be the roadblock I'm about to hit, but your code is closer to where Im trying to get too.
    I suppose float H should equal Vector3 A in some fashion.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,522