我有一个画布,我正在使用地理位置,谷歌地图和openweathermap来获取用户所在的天气。天气将被采取并导致我正在制作的游戏也使用那天气......
如何检查在画布上生成的两个正方形是否重叠?这是下雨的代码,目前看起来不像下雨......
function rectangle(x, y, w, h) {
var randomx = Math.floor(Math.random() * canvas.width - 50);
this.x = randomx || x || 0;
this.y = y || 0;
this.w = w || 0;
this.h = h || 0;
this.expired = false;
this.draw = function() {
cx.fillStyle = "blue";
cx.fillRect(this.x, this.y, this.w, this.h);
};
this.update = function() {
this.y++;
if (y > canvas.height) {
this.expired = true;
}
};
}
var rectangles = new Array();
function newRect() {
rectangles.push(new rectangle(window.randomx, window.y, 10, 10));
}
var timing = 0;
function loop() {
cx.clearRect(0, 0, canvas.width, canvas.height);
if (timing % 10 === 0) {
newRect();
}
for (var i = 0, l = rectangles.length; i < l; i++) {
rectangles[i].update();
rectangles[i].draw();
if (rectangles[i].expired) {
rectangles.splice(i, 1);
i--;
}
}
timing++;
requestAnimFrame(loop);
}
loop();
我的假设是,我需要执行'命中测试'以查看数组中的两个矩形是否在同一个边界...我猜我的this.draw和this.update函数在哪里我应该做点什么像...
this.hitTest = function () {
//Maths to check here
};
然后在forloop做...
rectangles[i].hitTest();
但我不确定数学或从哪里去......
任何帮助将不胜感激,提前谢谢!
答案 0 :(得分:3)
您可以像这样扩展rectangle
对象:
function rectangle(x, y, w, h) {
... existing code here ...
}
rectangle.prototype.intersects = function(rect) {
return !( rect.x > (this.x + this.w) ||
(rect.x + rect.w) < this.x ||
rect.y > (this.y + this.h) ||
(rect.y + rect.h) < this.y);
}
基于Daniel Vassallo的this code,为你的对象所采用。
现在只需在要比较的矩形上调用该函数:
if ( rectangles[x].intersects(rectangles[y]) ) {
... they intersect ...
}
要检查新矩形是否与现有的矩形相交:
function isOverlapping(myNewRect, rectangles) {
for(var i = 0, r; r = rectangles[i]; i++) {
if (myNewRect.intersect(r)) return true;
}
return false;
}