how to set character frame of spritesheet in phaser js?

Viewed 82

how to set frame of character? here is my code

  this.load.spritesheet(`dude-1`, `../src/assets/Character/ch-1.png`, {
        frameWidth: 72,
        frameHeight: 92,

    });

main logic code is here

this.player = this.physics.add.sprite(100, -500, this.charSelect).setOrigin(1, 1);
    
this.player.body.setGravityY(1700);
this.player.setBounce(0.1);

this.physics.add.existing(this.player).body.setSize(15, 90, ).setOffset(20, 0)

this.anims.create({
    key: "left",
    frames: this.anims.generateFrameNumbers(this.charSelect, { start: 6, end: 10 }),
    frameRate: 10,
    repeat: -1,
});

this.anims.create({
    key: "turn",
    frames: [{ key: this.charSelect, frame: 5 }],
    frameRate: 10,
});

this.anims.create({
    key: "right",
    frames: this.anims.generateFrameNumbers(this.charSelect, { start: 0, end: 4 }),
    frameRate: 10,
    repeat: -1,
});
cursors = this.input.keyboard.createCursorKeys();

this.physics.add.collider(this.player, this.platformGroup);
this.player.body.setCollideWorldBounds(true);
this.physics.world.setBounds(0, 0, (config.width) - 10, config.height, true, true, false, true);

here is output and issue. how to set the frame of character?

enter image description here

1 Answers

The problem is, that the phaser-image / frame size is too big (or the actual image is to small). Check the frame size (frameWidth and frameHeight) and the actual image size, that could solve your problem.

Here a short demo:
It loads the same spritesheet, once with the correct frameWidth / frameHeight size and once with a too big size.

document.body.style = `padding:0;margin:0;`;

class Example extends Phaser.Scene {
    constructor() {
        super();
    }

    preload() {
        this.load.spritesheet('mummyCorrectSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 37, frameHeight: 45 });            
        this.load.spritesheet('mummyWrongSize', 'https://labs.phaser.io/assets/animations/mummy37x45.png', { frameWidth: 50, frameHeight: 50 });
    }

    create(){
        // the "const" variables show the the wrong and right sprite creation
        const wrongSizeSprite= this.add.sprite(50, 40, 'mummyCorrectSize').setOrigin(0);
        const rightSizeSprite = this.add.sprite(50, 120, 'mummyWrongSize').setOrigin(0);
        
        this.add.text(50, 10, 'Right size: single sprite/frame shown');
        this.add.text(50, 100, 'Wrong size: the whole image is shown');
    }
}

const config = {
    type: Phaser.AUTO,
    width: 500,
    height: 180,
    scene: [ Example ]
};

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

Related