2
\$\begingroup\$

Given three points on the same Y plane;

  • A ship
  • A point along the ships heading
  • A mouse cursor

How can I find which direction and angle the mouse cursor is from the ships heading?

I have a limited turn speed on the ship - so I can not simply point the ship at the mouse, but tell it to steer left or right until it faces in the same direction of the mouse.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

ship_dir =point_on_heading-ship_pos(ition) //vector ship is heading in
mouse_dir=mouse_pos-ship_pos               // vector from ship to mouse position

You can find the angle between these two vectors;

ship_dir.Normalize(); //divide by length
mouse_dir.Normalize();//divide by length
dot_prod=DotProduct(ship_dir,mouse_dir);
angle=acos(dot_prod); //cos-1, this will give angle between two vectors

BUT that doesn't tell you which way to turn (left or right)(positive or negative)(clockwise or anti-clockwise).

You also need to consider the normal to the mouse_dir. The dot product between two vectors is positive if the angle is less than 90deg.

mouse_normal=(-mouse_dir.y,mouse_dir.x);
dot_prod=DotProduct(ship_dir,mouse_normal);
if(dot_prod>0) //+ive value means the angle is <90deg therefore, ship_dir is on 'left'side of mouse dir, so clockwise is shortest route
    rotate clockwise;
else 
    rotate anti_clockwise;

enter image description here

\$\endgroup\$
1
  • \$\begingroup\$ perfect! for those following at home, to match my exact problem, my mouse normal is set as mouse_position(z,1,x); \$\endgroup\$ Commented Nov 4, 2012 at 12:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .