Custom Player Sprite Class
An example of encapsulating player logic, such as movement, animations, and jumping, within a class that extends the Arcade Physics Sprite.
1024 × 768
import ANIMATION_KEYS from "../animationKeys.js";
import AUDIO_KEYS from "../audioKeys.js";
import SPRITE_KEYS from "../spriteKeys.js";
export class Player extends Phaser.Physics.Arcade.Sprite
{
jumpVelocity = -520;
moveVelocity = 200;
gameUiScene;
isPlayer = true;
constructor(scene, x, y)
{
super(scene, x, y, SPRITE_KEYS.DUDE);
scene.add.existing(this);
scene.physics.add.existing(this);
this.gameUiScene = scene.scene.get('GameUi');
this.setCollideWorldBounds(true);
this.setDepth(100);
}
moveLeft ()
{
this.setVelocityX(-this.moveVelocity);
this.anims.play(ANIMATION_KEYS.PLAYER_LEFT, true);
if (this.body.touching.down) this.gameUiScene.playAudio(AUDIO_KEYS.PLAYER_STEP, false);
}
moveRight ()
{
this.setVelocityX(this.moveVelocity);
this.anims.play(ANIMATION_KEYS.PLAYER_RIGHT, true);
if (this.body.touching.down) this.gameUiScene.playAudio(AUDIO_KEYS.PLAYER_STEP, false);
}
idle ()
{
this.setVelocityX(0);
this.anims.play(ANIMATION_KEYS.PLAYER_IDLE);
}
jump ()
{
if (this.body.touching.down)
{
this.setVelocityY(this.jumpVelocity);
this.gameUiScene.playAudio(AUDIO_KEYS.PLAYER_JUMP);
}
}
}More in GameObjects13 examples
Dynamic Texture PlatformsDemonstrates creating custom-sized platform sprites by stamping tile textures onto a Dynamic Texture and configuring them as static Arcade Physics bodies.Floating Score TextDemonstrates a custom BitmapText class that animates upwards and automatically destroys itself using a Tween, creating a classic floating score effect for points.Hamster Player ClassA demonstration of extending the Arcade Physics Sprite class to create a controllable character with encapsulated movement, jumping, and animation logic.Key Sprite ClassA custom Sprite class for a collectible item that demonstrates a floating tween animation, cross-scene audio triggering, and self-destruction.