How can I load texture in scenes subclass?

39 Views Asked by At

I have a loading scene which preloads my textures..

preload() {
  this.load.image("ship", "./assets/ship.png")...

and a level-scene with a custom player object..

export class Player extends Phaser.Physics.Matter.Sprite {

constructor(scene: Scene) {
    super(scene.matter.world, 64, 64, "ship", undefined, {
      friction: 0.025,
      frictionAir: 0.25,
   }); ...

but inside that player object i can´t set textures, it has no effect.

in level-scene:

create(){
  this.player = new Player(this);...

how can i load textures inside the player subclass of the level-scene? thanks.

1

There are 1 best solutions below

1
winner_joiner On BEST ANSWER

You just have to add the sprite to the scene, with the command scene.add.existing(this); currently only the physics object is added.

Here a small Demo:

document.body.style = 'margin:0;';

class Player extends Phaser.Physics.Matter.Sprite {
    constructor(scene) {
        super(scene.matter.world, 64, 64, "blue", undefined, {
            friction: 0.025,
            frictionAir: 0.25,
        }); 

        scene.add.existing(this);
    }
}

class Example extends Phaser.Scene {
    preload () {
        this.load.image('blue', 'https://labs.phaser.io/assets/sprites/columns-blue.png');
    }

    create () {
        //const rect = this.matter.add.image(200, 50, 'blue');
        this.player = new Player(this);
     
    }
}

const config = {
    width: 500,
    height: 185,
    physics: {
        default: 'matter',
        matter: {
            debug: true
        }
    },
    scene: Example
};

const game = new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>