Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Getting Points On A Line Between 2 Vectors

Discussion in 'Physics' started by steviebob, Feb 1, 2015.

  1. steviebob

    steviebob

    Joined:
    Jul 15, 2014
    Posts:
    21
    Hi Guys,
    How can you get the coordinates in a line between 2 points?
    e.g. suppose I have 2 points and want to get a vector3 every x units in a straight line from 1 to the other, how would I go about this?

    The purpose is so I can draw a path by putting textures down at the points along the line between the 2 points (Not sure if this is the right way to do it or not ?).

    Once I've had a bit more practice, I'll make fancier curved paths, but for now I need to stick to the simple bits (Presumably what I end up learning from this post would still be applicable).
     
  2. Uberpete

    Uberpete

    Joined:
    Jan 16, 2014
    Posts:
    78
    Okay, time to take a trip back to middle-school maths :cool:

    First, say we have two vectors, A and B

    Code (CSharp):
    1. Vector3 a;
    2. Vector3 b;
    You'd first want to get the vector between the points:

    Code (CSharp):
    1. Vector3 lineWeWant = b-a;
    Now, divide the vector by the amount of points you want (say, x points) and then run that through a for-loop:

    Code (CSharp):
    1. int x = 23; // I WANT 23 POINTS
    2. GameObject pointPrefab; //some random prefab
    3.  
    4. for (int i =0; i <x; i++){
    5.  
    6. Instantiate (pointPrefab, a + (lineWeWant/x * i), transform.rotation);
    7.  
    8. }
    Hope this helps :p
     
    chelnok likes this.
  3. steviebob

    steviebob

    Joined:
    Jul 15, 2014
    Posts:
    21
    ahhh, you're a star, thank you very much.
    I know this is probably something I learned in school (I was almost too embarrassed to post the question) but I couldn't find a simple answer with my googleFoo.

    There was 1 more thing that I'd like to know.
    How can I supply a Vector3 and determine whether or not it is somewhere along the line between 2 points?

    Can you point me to any resources where I can do some additional reading?
     
  4. steviebob

    steviebob

    Joined:
    Jul 15, 2014
    Posts:
    21
  5. Uberpete

    Uberpete

    Joined:
    Jan 16, 2014
    Posts:
    78
    Took a quick glance, looks like it should. If not, feel free to PM me - I've just done the topic at school so its definitely fresh in my mind XD