I'm having a little trouble calculating this angle and I'm hoping one of you geniuses can help me.
I have a game with a cannon that can be at any spot in the game world. Using OpenGL's matrix transformations, I want the cannon's texture to rotate to face in whatever direction the player puts his finger. To do this, I need to calculate an angle to send to the rotation matrix.
Currently I'm having a little trouble calculating the angle correctly.
See the figure:
Legend: A) A constant unit vector that always points toward the top of the screen. B) A point that is set based on where the user clicks the screen. theta) the angle I need to measure
As you can see, I'm using a constant unit vector that always points up as a baseline (A). What my algorithm needs to do is correctly measure the angle (theta) between A and B.
Here's the code that sets the target's position:
public void setTarget(Vector2 targetPos) {
//calculate target's position relative to cannon
targetPos = sub(targetPos, this.position);
//replace target
this.target = targetPos;
//calculate new angle
//This is broken
this.cannonAngle = findAngleBetweenTwoVectors(POINT_UP, target);
The "findAngleBetweenTwoVectors" method is what doesn't seem to be working. It's code is here:
public static float findAngleBetweenTwoVectors(Vector2 baseVec, Vector2 newVec) {
//first, make copies of the vectors
Vector2 baseCopy = new Vector2(baseVec);
Vector2 newCopy = new Vector2(newVec);
//next, ensure they're normalized
baseCopy.nor();
newCopy.nor();
//the arc-cosine is the angle between the two vectors
//this is used as the "cannonAngle" value (does not work)
return (float) Math.acos(newCopy.dot(baseCopy));
}
I know this is likely a vector math problem, I just can't seem to get the angle calculation right.
Thanks in advance for the help.