每次我尝试向正确的方向移动桨时都会收到此错误!!
Uncaught TypeError: paddle.moveRight is not a function at 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();
});
}
}
<小时/>
当我按下右箭头按钮时,桨应该向右移动
最佳答案
let paddle = new Paddle();
new InputHandler(Paddle)
您正在将 Paddle
类传递到 InputHandler
的构造函数中。然后,您在该类上调用 moveLeft
。
您可能想传递该类的实例。
let paddle = new Paddle();
new InputHandler(paddle);
关于javascript - 我无法从类中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55319620/