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

Direction Vector3 from a point and angle in eulers

Discussion in 'Scripting' started by mirzahat, Aug 25, 2015.

  1. mirzahat

    mirzahat

    Joined:
    Dec 21, 2014
    Posts:
    53
    Hello

    I have a ball positioned as Vector3(x, x, x).

    I was able to get the direction of the ball to the mouse clicked position with:

    Code (csharp):
    1.  
    2. Vector3 direction = Direction (clickPos2 - startPos);
    3.  
    Where the method is:

    Code (csharp):
    1.  
    2. public Vector3 Direction(Vector3 position) {
    3.         return new Vector3(position.x / Length(position.x, position.y), position.y / Length(position.x, position.y), position.z);  
    4.     }
    5.  
    Now I have an angle in eulers and I want that the ball goes to the direction of the angle.

    But how I calculate it'

    The game is played in 2d so actually only x and y is needed, z stays the same.

    Mirza
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    No need for that function - mathematics will set you free:
    Code (csharp):
    1.  
    2. Vector3 direction = clickPos2 - startPos;
    3. float angle = Mathf.Atan2(direction.y, direction.x);
    4.  
    5. float xVelocity = Mathf.cos(angle) * speed;
    6. float yVelocity = Mathf.sin(angle) * speed;
    7.  
     
  3. mirzahat

    mirzahat

    Joined:
    Dec 21, 2014
    Posts:
    53
    Hello,

    thanks for answer.

    I think you misunderstood the question a bit:

    1. I have a point x, y

    2. I have an angle of 45 in eulers.

    3. How do I get the direction vector of the point to the angle?

    Mirza
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Picture? Pictures are essential to communicating geometry questions.
     
  5. mirzahat

    mirzahat

    Joined:
    Dec 21, 2014
    Posts:
    53
  6. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    If the angle is always relative to the 2d world axis and not relative to the direction of movement, just take the second part of @GroZZleR's code. Cos(angle) will tell you how far to move in x-direction, sin(angle) how far in y-direction. The resulting direction vector will have the magnitude of 1. That's why he also multiplied it by speed.