我目前正在开发一个小游戏,当我遇到障碍物时,我正试图实现一个“游戏结束”功能。但每次我添加实现该功能的所有代码时,它都会破坏一切。如果有人能帮助我,我将不胜感激。我不确定问题出在哪里。
下面是完整的代码(只有js部分):
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(30, 30, "red", 225, 225);
myObstacle = new component(40, 40, "green", 300, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1000;
this.canvas.height = 890;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.moveAngle = 0;
myGamePiece.speed = 0;
myObstacle.update();
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.moveAngle = -2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.moveAngle = 2; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speed= 2; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speed= -2; }
myGamePiece.newPos();
myGamePiece.update();
}
startGame();
发布于 2019-02-20 22:53:35
尝试修复这个问题:第14行和17行缺少分号,让我们看看……
发布于 2019-02-20 23:05:29
您所要求的是2D碰撞检测。如果你要使用正方形,那就相当简单了。基本上,将这两个正方形与以下内容进行比较:
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y) {
// collision detected!
}
摘自:https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
此代码仅适用于没有任何旋转的正方形。对于旋转,您必须根据旋转角度分解sin/cos/tan的三角函数。
二维碰撞有多种解决方案。一种方法,基于我个人使用过的地理栅栏,是获取对象1的每个点,并将其与对象2的每个边进行比较。如果一个点的一个方向上有奇数个边(例如,向右),那么它就在对象内部。您将对每个点迭代此函数,如果有任何返回奇数,则执行return true
。然后,您应该对对象2点重复处理反向过程。
这称为多边形中的点方法:
https://en.wikipedia.org/wiki/Point_in_polygon
这适用于多边形形状,但一旦使用曲线,它就会变得更加困难。但是,通常情况下,游戏使用"hitboxes“,因为它的本质过于简单。
编辑:要注意的是,如果点击框大小相同,则此多边形中的点可以工作,但如果您可以相互重叠两个矩形,则必须将Object1的每一边的交点与Object2中的边进行比较。
https://stackoverflow.com/questions/54788865
复制相似问题