- Home /
The question is answered, right answer was accepted
Calculating the Angle between two vectors
I am making a 2D game where I have to aim a grapple onto a wall. I need help calculating the angle, because I want the game to look like this:
90 degrees
^
|
|--------->0 degrees
the vertical component is the y-axis, and the horizontal component is the x-axis
Vector3.angle? Vector3.dot, or Quaternion.dot, is probably faster under the right circumstances, if you enjoy trigonometry. If the ground is always flat, could use arctangent ($$anonymous$$athf.Atan2, but only if you need the speed-up and like trig.)
Pretend a bowman is shooting an arrow. I want to simulate him ai$$anonymous$$g the arrow between 0(straight across the x-axis) and 90 degrees (straight up the y-axis) with the help of the mouse drag
Answer by almo · May 20, 2011 at 06:07 PM
Mathf.Acos(Vector3.Dot(vector1.normalized, vector2.normalized));
should give you the angle between two vectors. This answers the title of your question, but the body of your question is very vague.
Answer by Owen-Reynolds · May 21, 2011 at 03:56 PM
For angle to the mouse in a 2D, need to know the mouse is in screen Pixels and the bow is in world units. Can convert the bow to screen pixels, or can convert the mouse to the world position (in 3D the world position of the mouse is anywhere on the line it shoots, for 2D it's just a point.) These are some fo the commands (untested):
Vector3 bowP = Camera.main.WorldToScreenPoint(bowWoldPos);
// x,y are in pixels. z can be ignored
Vector3 aimP = Input.MousePosition();
// Same units: x,y are in pixels
// acos (see other answer) for the angle
OR, to use world pos:
Vector3 aimWorldP = Camera.main.ScreenToWorldPoint(Input.MousePosition());
aimWorldP.z = bowPosition.z;
bow.LookAt(aimWorldP);
// bow.forward now aims at the mouse