gpt4 book ai didi

javascript - 当我遇到重新启动的障碍时,我将如何添加一个事件

转载 作者:可可西里 更新时间:2023-11-01 14:59:36 26 4
gpt4 key购买 nike

我目前正在开发一个小游戏,我试图在遇到障碍物时实现“游戏结束”功能。但每次我添加所有代码来实现该功能时,它都会破坏一切。如果有人能帮助我,我将不胜感激。我不确定是什么问题。

完整代码如下(仅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();

最佳答案

尝试解决这个问题:您在第 14 和 17 行缺少分号让我们看看...

关于javascript - 当我遇到重新启动的障碍时,我将如何添加一个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com