我有一个画布,正在使用地理定位、谷歌地图和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();
我的假设是,我需要执行一个“命中测试”来查看数组中的两个矩形是否在同一周长内... 我猜想,在这个.draw和.update函数所在的位置,我应该做些什么...
this.hitTest = function () {
//Maths to check here
};
然后在for循环中做...
rectangles[i].hitTest();
但是我不确定数学部分或接下来该怎么做...
任何帮助将不胜感激,谢谢!