# Rotate heading relative to agent's local space

I'm having a little trouble translating a point in my game's world space to an object's local space.

I have a cannon in my game with a normalized heading vector that's always supposed to point in the direction of a target. The target is set by an incoming screen touch event.

My problem is that the coordinates I get from the incoming touch events are relative to the game world's axis centered at the world's origin, not relative to the cannon's position like I need. The angle I calculate to rotate the heading is relative to the world's X-axis, not the cannon's local X-axis, this means I can never rotate the heading by anything outside of 0 < x < 90.

I hope my crude drawing conveys what I mean. In the picture below, A is the cannon's position (with the blue heading vector), and B is the target's location (set by an event). The green line represents the angle the game is giving me, and the angle between red line and the heading is what I need to find (the little curved blue arrow).

Here's the code I use to calculate the heading:

 float xDistance = target.x - position.x;
float yDistance = target.y - position.y;
float angleToTurn = (float) Math.atan2(yDistance, xDistance);



Thanks in advance. Any help is greatly appreciated.

• You code and your description contain no reference to a value for the current heading of the cannon. To find the needed angle change, you would need the current value to be saved somewhere. Then you would simply subtract it from the direction you calculate from position to target. Feb 17 '15 at 6:16
• Yes they do. The current heading of the cannon is the blue line in my drawing, and in my code the "vec2RotateAroundOrigin" method is supposed to take the heading and rotate it by the angle. I'm unsure as to what you mean. Feb 17 '15 at 6:45
• So you already know how to calculate a heading, and you already have a current heading? Then only step left is to subtract one angle from another. It's not clear where your solution is failing. Feb 18 '15 at 5:44

This is fairly easily solved with a bit of vector math.

You're interested in the vector from the cannon to the event point, but you have the cannons position and the event point from origo. Adding the cannons position to the vector pointing from the cannon to the event would equal the event from origo vector.

Or in other words:

OrigoToEvent = OrigoToCannon + CannonToEvent
OrigoToEvent - OrigoToCannon = OrigoToCannon + CannonToEvent - OrigoToCannon
OrigoToEvent - OrigoToCannon = (OrigoToCannon - OrigoToCannon) + CannonToEvent
OrigoToEvent - OrigoToCannon = CannonToEvent
CannonToEvent = OrigoToEvent - OrigoToCannon


From there on it's simply a matter of calculating the angle between the two vectors. I hope that is enough to get your code working