make my player move in a custom class

hi there ! i’m new to phaser and javascript and i can’t figure out how to make my player move in a custom class

//fish.js

class Fish extends Phaser.GameObjects.Sprite{

    constructor(scene, x, y){

        super(scene, x, y, 'fish', '3'); 

        this.scene.add.existing(this);
        scene.physics.world.enableBody(this);
        this.body.setGravityY(660);
        this.body.setCollideWorldBounds(true);

    }
    

      update(){
          if (scene.cursors.right.isDown) {
             this.body.setVelocityX(190); 
            } else if (scene.cursors.left.isDown) { 
                this.body.setVelocityX(-190); 
            } else { 
                this.body.setVelocityX(0);
            }
      }
}

//scene.js

this.cursors = this.input.keyboard.createCursorKeys();
this.player = this.add.existing(new Fish(this, 100, 0));

or should i create move functions and call them in scene.js?(not sure how to do that either…) can anyone help?

In scene change to:

this.player = new Fish(this, 100, 0);

because you already add it in the Fish class:
inthe Fish class:

class Fish extends Phaser.GameObjects.Sprite{

    constructor(scene, x, y){

        super(scene, x, y, 'fish', '3'); 
        this.scene = scene; // <-- add this line
        this.scene.physics.world.enable(this); // <-- change this line too
        this.scene.add.existing(this);
        this.body.setGravityY(660);
        this.body.setCollideWorldBounds(true);

    }
    

      update(){
          if (this.scene.cursors.right.isDown) { // <-- you must use this.scene instead of scene
             this.body.setVelocityX(190); 
            } else if (this.scene.cursors.left.isDown) {  // <-- same here
                this.body.setVelocityX(-190); 
            } else { 
                this.body.setVelocityX(0);
            }
      }
}
1 Like