Mahmoud Hammmad
Mahmoud Hammmad

Reputation: 23

i cant run a function from a class

i get this error every time i try to move paddle at right direction !!

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();
    });
  }
}

the paddle should go to right when i press the right arrow button

Upvotes: 0

Views: 106

Answers (1)

chris.va.rao
chris.va.rao

Reputation: 373

let paddle = new Paddle();
new InputHandler(Paddle)

You are passing the Paddle class into the constructor of InputHandler. You are then calling moveLeft on that class.

You probably meant to pass in the instance of the class.

let paddle = new Paddle();
new InputHandler(paddle);

Upvotes: 1

Related Questions