Jump to content

Moving a custom class that extends a Sprite


MeMyMo
 Share

Recommended Posts

I haven't been able to figure this out. I have a "Player" class that extends Sprite:

export default class Player extends Phaser.GameObjects.Sprite{
   constructor(scene, x, y, config) {
    super(scene, x, y, config.key);

    this.scene = scene;
    this.lastAnim = null;
    this.vel = 200;

    this.scene.physics.world.enable(this);
    this.scene.add.existing(this);

    const { LEFT, RIGHT, UP, DOWN } = Phaser.Input.Keyboard.KeyCodes;
    this.keys = this.scene.input.keyboard.addKeys({
      left: LEFT,
      right: RIGHT,
      up: UP,
      down: DOWN,
    });
  }

  preUpdate (time, delta) {
    super.preUpdate(time, delta);

    const keys = this.keys;
    let animationName = 'player-idle';

    if (keys.left.isDown) {
      this.body.setVelocityX(-this.vel);
      this.setFlipX(true);
    } else if (keys.right.isDown) {
      this.body.setVelocityX(this.vel);
      this.setFlipX(false);
    }

    if (keys.up.isDown) {
      this.body.setVelocityY(-this.vel);
    } else if (keys.down.isDown) {
      this.body.setVelocityY(this.vel);
    }

    // TODO: Clean this up
    if (keys.up.isDown || keys.down.isDown || keys.left.isDown || keys.right.isDown) {
      animationName = "player-walk";
    } else {
      animationName = 'player-idle';
    }

    if(this.lastAnim !== animationName) {
      this.lastAnim = animationName;
      this.anims.play(animationName, true);
    }
  }
}

I instantiate it in the "create" method of the scene:
 

this.player = new Player(this, 300, 300, {key: 'player'});

The Sprite animates and everything, but it just stays in the same place.

My game setup:

const gameConfig = {
  width: 1024,
  height: 768,
  scene: GameScene,
  pixelArt: true,
  zoom: 2,
  physics: {
    default: 'arcade',
    arcade: {
        gravity: { y: 0 },
        debug: false
    }
  },
};

I've seen examples that create an update method then call it in the scene update loop, but shouldn't  preUpdate be the same? Any help appreciated!

Link to comment
Share on other sites

  • 2 years later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...