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. Dismiss Notice

A wee vector math question

Discussion in 'Scripting' started by jtsmith1287, Feb 23, 2015.

  1. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    Currently I do the following (pseudo code btw) but I'd like to trim it down/simplify if possible:

    Code (CSharp):
    1.  
    2. float distance = Vector3.Distance(position, targetPosition);
    3. float distPercent = DesiredDistance / distance
    4.  
    5. float x_change = position.x - targetPosition.x;
    6. float z_change = position.z - targetPosition.z;
    7.  
    8. float newX = targetPosition.x + (x_change * distPercent);
    9. float newZ = targetPosition.z + (z_change * distPercent);
    10.  
    11. // Maintain DesiredDistance from target all times, backing away when needed.
    12. Destination = new Vector3(newX, 0, newZ);
    13.  
    This works absolutely beautifully, and don't want to change the behaviour at all. However, it seems inefficient, as well as messy, imho. I'd like to clean it up. Some of you may be wondering if it's casing problems and if I need to optimize at all, blah blah... not the point here. I don't know math very well and I've spent days trying to understand it to get the behaviour I want, and now I want to know is there some trig fucntion that does this for me now that I've learned the basics/core of what I wanted to achieve. I'll be implementing much more of this in the future and this current method doesn't seem very flexible to me.

    Thanks in advance for the help!
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    I believe this is what you're looking for.
    Code (csharp):
    1. Vector3 direction = position-targetPosition;
    2. Destination = targetPosition+direction.normalized*DesiredDistance;
     
  3. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    Hot damn, I think you're right. I was also wanting to implement steering behaviours into this and I believe this would make that implementation much easier. Ha! Excited to get home and try it now. Stupid 8 hour job!!! I just got heeerrreee!