I have been working on a shooter game in C++, and am trying to add a feature whereby missiles shot must be within 90 degrees (PI/2 radians) of the direction the ship is facing. The missiles will be shot towards the mouse. My idea is that the ship's angle of rotation is compared with the angle between the ship and the mouse (std::atan2(mouseY - shipY, mouseX - shipX)), and if the difference is less than PI/4 (45 degrees) then the missile can be fired. However, I can't seem to get this to work. The ship's angle of rotation is increased and decreased with the A and D keys, so it is possible that it isn't between 0 and 2*PI, hence the use of fmod() below.


float userRotation = std::fmod(user->Angle(), 6.28318f);
if (std::abs(userRotation - missileAngle) > 0.78f) return;

Any help would be appreciated. Thanks!

  • \$\begingroup\$ What does it do? What is wrong? \$\endgroup\$
    – wondra
    Commented Aug 24, 2014 at 22:31
  • \$\begingroup\$ It only allows me to fire at seemingly random angles which do not seem to have any correspondence to the angle of the ship. When the ship rotates far enough I am not able to fire at all. \$\endgroup\$ Commented Aug 26, 2014 at 21:43

1 Answer 1


The easiest way to check if an object faces a point is to use to compare the angle of normalised vectors, in your case, the normalised forward vector of the ship and the normalised fire vector.

To get the forward direction of the ship you can do the following. Assuming the ship is facing down X+ axis when the ship angle is 0, the forward vector is equal to:

forward.x = cos(shipAngle); 
forward.y = sin(shipAngle);

And the fire vector:

fireVector.x = mouseX - shipX;
fireVector.y = mouseY - shipY;
fireVector = normalise(fireVector);

You can then use the vector dot product to get the angle.

float dotProduct = dot(forward, fireVector);

Compare the angle between 0 and 90 degrees.

if( dotProduct >= 0.0f ) 

By using normalised vectors we can use the fact that the dot product returns the cosine of the angle. As cos(90) = 0 we compare if the dot product is greater or equal to 0 before firing.

  • \$\begingroup\$ dot product is the key! \$\endgroup\$
    – jhocking
    Commented Aug 25, 2014 at 12:13
  • \$\begingroup\$ Thanks for this! I wouldn't have been able to figure out how to do this myself. I would rate this up but I can't since I haven't got enough reputation :( \$\endgroup\$ Commented Aug 26, 2014 at 21:05

You must log in to answer this question.

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