我正在开发一款游戏,每次点击画布时,玩家(位于画布上(都会朝那个方向投篮。现在的工作原理是,当我在画布上点击时,它会创建球,并随着我的不断点击而前进,但它应该在第一次点击后自动向前移动。我尝试过使用requestAnimationFrame
,但出现了范围问题。
这是相关的代码:Game
类:
class Game {
constructor(props) {
// ...
this.balls = []
this.canvas.addEventListener('mousedown', (e) => {
this.handleMouseClicks(this.canvas, e)
});
}
handleMouseClicks(canvas, e) {
if () {
} else {
this.balls.push(new Ball());
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
// draw all the balls
this.balls.forEach((ball) => {
ball.animateBall();
});
// draw the player after clearing the canvas
this.player.drawPlayer(this.playerPosX, this.playerPosY);
}
}
}
Ball
类:
class Ball {
constructor(props) {
// ...
}
updateBall() {
this.ballPosX = this.ballPosX + this.velocity.x
this.ballPosY = this.ballPosY + this.velocity.y
}
drawBall() {
this.angle = Math.atan2(this.mouseClickPosY - this.cannonPosY, this.mouseClickPosX - this.cannonPosX);
this.velocity = {
x: Math.cos(this.angle),
y: Math.sin(this.angle)
};
this.ballRadius = 2;
this.ctx.beginPath();
this.ctx.arc(this.ballPosX, this.ballPosY, this.ballRadius, 0, Math.PI * 2, false);
this.ctx.closePath();
this.ctx.fillStyle = this.color;
this.ctx.fill();
}
animateBall() {
this.drawBall();
this.updateBall();
}
}
我试图做的是在Game类中移动动画部分,这样我就可以使用requestAnimationFrame
:调用它
handleMouseClicks(canvas, e) {
if () {
} else {
loop();
function loop(){
this.balls.push(new Ball());
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
// draw all the balls
this.balls.forEach((ball) => {
ball.animateBall();
});
// draw the player after clearing the canvas
this.player.drawPlayer(this.playerPosX, this.playerPosY);
requestAnimationFrame(loop);
}
}
}
但这并没有像预期的那样起作用
如果使用function
关键字定义函数,它将在全局范围中定义。如果您希望函数将Game实例用作this
,则可以使用箭头函数。箭头函数将函数的上下文绑定到它们在中定义的上下文。
让我们为Game
类定义一个draw()
方法。
class Game {
constructor() {
// ...
this.draw();
}
// ...
draw() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// draw all the balls
this.balls.forEach((ball) => {
ball.animateBall();
});
// draw the player after clearing the canvas
this.player.drawPlayer(this.playerPosX, this.playerPosY);
// Here, "() => { /* function body */ }" is an arrow function example
window.requestAnimationFrame(() => this.draw());
}
}