I have a ship, the ship travels towards a heading (vector3, blue arrow) with an arbitrary speed.

The ship has a weapon on the side, the weapon can point in any direction, except straight forward/backwards from the ship heading. (In example image the weapon is a perpendicular 90* right).

The weapon has a firing arc, in n degrees (so, n/2 degrees in either side from the weapon "point direction").

Given a target at any position on the same side of the ship as the weapon (red circle), how do I rotate the ships heading so that when oriented towards the new heading (in this example, the yellow arrow), the target is inside the bounds of the firing arc? (The ship cannot rotate on the spot, it turns by driving forward towards a heading, like a simplified aircraft)

While my game is set in full 3D, I think a 2D solution will be more than enough. I use Unity, and C#, but I'm thankful for any solutions.

enter image description here

Edit: To clarify, I am looking for the "math-based" solution, collision-checks etc isn't really feasible.


1 Answer 1


This will basically boil down to math.

Unless your ship moves in the meantime, then there is a really easy approach: just let the ship turn at max turn rate and check every now and then if the target is inside the fire angle (using collision detection between the target and the area that your green lines draw up.

If not, and you want to know the necessary new heading , you have to set up the corresponding equation, which is: [In assumption that your ship hat 1 discrete center from which everything is calculated]

new heading b2 = the angle between g1 (the left green line, if the target is left of the fire cone) and t1 (which is the line drawn from the target to the center of the ship) added to b0

Getting the angle between vectors should be rather trivial, as well as modifying a vector by an angle. Maybe there is a way to bypass angles altogether by using normalized vectors or something, but to be honest, I slept during that part of math class. [Also you might have to double check where what has to be added vs subtracted, because that all depends on where what is etc]

  • \$\begingroup\$ Thanks, the math-based approach is what I'm after, I just can't wrap my head around how to rotate a vector3 by an angle. \$\endgroup\$
    – ag4w
    Nov 22, 2018 at 15:32
  • \$\begingroup\$ @ag4w Try Vector3.RotateTowards \$\endgroup\$
    – Philipp
    Nov 22, 2018 at 16:14
  • \$\begingroup\$ @ag4w alternatively, if you wanna/have to do it manually, check out this one: matthew-brett.github.io/teaching/rotation_2d.html After that its just implementing that formula in whatever language you use \$\endgroup\$
    – Hobbamok
    Nov 23, 2018 at 10:21

You must log in to answer this question.

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