我試圖顯示在矩形中哪裏是玩家瞄準我的遊戲。他是這樣一個正方形:從不在矩形中間的點以角度查找矩形邊界點
我發現了一個algorithm to find rectangle point by angle,應用它,結果是錯誤的(真正的遊戲截圖):
我很快就意識到,這是因爲球員不在矩形的中心。所以我用我的觀點取代了algorighm的中心點。但結果是通過恆定距離剛剛移位後的點:
所以,我想我現在的算法,需要的不僅僅是一個變化更多。我的代碼:
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;
}
還有哪些地方需要應用參考點位置才能使其工作?它是而不是要求這個函數返回合理的結果,如果點在矩形之外。