I am trying to display where, in a rectangle, is player aiming in my game. He's in such a square:
I found an algorithm to find rectangle point by angle, applied it and the results were wrong (real game screenshot):
I soon realized this is because player is not in the center of the rectangle. So I replaced the center point in the algorighm with my point. But the result is just shifted point by constant distance:
So I guess my current algorithm needs more than just one change. My code:
function boudaryatangle(theta, point) {
// reduce the theta
theta = theta % 360;
// force it to be the positive remainder, so that 0 <= theta < 360
theta = (theta + 360) % 360;
// force into the minimum absolute value residue class, so that -180 < theta <= 180
if (theta > 180)
theta -= 360;
// Convert to radians
theta = (theta * Math.PI / 180);
// Get a rectangle that has width and height properties
var rect = this.game.pixels;
var width = rect.width;
var height = rect.height;
// If refference point wasn't provided as second argument
//TODO: MAKE IT WORK WITH OTHER THEN RECTANGLE CENTRE POINT!
if(typeof point=="undefined") {
point = new Float32Array(2);
point[0] = width/2;
point[1] = height/2;
}
// Here be mysterious math and stuff - all bellow explained here
var rectAtan = Math.atan2(height, width);
var tanTheta = Math.tan(theta);
// By default, region 1 and 3
var region = true;
var xFactor = 1;
var yFactor = 1;
if ((theta > -rectAtan) && (theta <= rectAtan)) {
yFactor = -1; // REGION 1
} else if ((theta > rectAtan) && (theta <= (Math.PI - rectAtan))) {
yFactor = -1; // REGION 2
region = false;
} else if ((theta > (Math.PI - rectAtan)) || (theta <= -(Math.PI - rectAtan))) {
xFactor = -1; // REGION 3
} else {
xFactor = -1; // REGION 4
region = false;
}
// If region 1, 3
if (region) {
point[0] += xFactor * (width / 2.); // "Z0"
point[1] += yFactor * (width / 2.) * tanTheta;
} else {
point[0] += xFactor * (height / (2. * tanTheta)); // "Z1"
point[1] += yFactor * (height / 2.);
}
return point;
}
Where else do I have to apply refference point location to get it to work? It's not required that this function returns sane results if point is out of the rectangle.