每次我尝试向正确方向移动桨时,都会收到此错误!!
未捕获的TypeError:paddle.moveRight不是HTMLDocument.InputHandler.document.addEventListener.event上的函数
// index.html
<html>
<head>title>Brick Breaker</title
><meta charset="UTF-8" />
</head>
<body>
<canvas id="gameScreen" width="800" height="600"></canvas>
<script type="module" src="src/index.js"></script>
</body>
</html>
// index.js
import Paddle from './paddle.js'
import InputHandler from './input.js'
let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");
let paddle = new Paddle();
new InputHandler(Paddle)
function gameLoop() {
ctx.clearRect(0, 0, 800, 600);
paddle.update();
paddle.draw(ctx);
requestAnimationFrame(gameLoop);
}
gameLoop()
// paddle.js
export default class Paddle {
constructor(){
this.width=150;
this.height=30;
this.maxSpeed =10;
this.speed=0;
this.position={
x:300,
y:500
}
}
moveRight() {
this.speed = this.maxSpeed;
}
draw(ctx) {
ctx.fillStyle = "#0ff";
ctx.fillRect(this.position.x, this.position.y, this.width, this.height);
}
update() {
this.position.x += this.speed;
}
}
// input.js
export default class InputHandler {
constructor(paddle) {
document.addEventListener("keydown", event => {
if(event.keyCode ==37)
paddle.moveRight();
});
}
}
当我按下向右箭头按钮时,桨应向右移
答案 0 :(得分:1)
let paddle = new Paddle();
new InputHandler(Paddle)
您正在将Paddle
类传递到InputHandler
的构造函数中。然后,您要在该课程上致电moveLeft
。
您可能打算传递类的实例。
let paddle = new Paddle();
new InputHandler(paddle);