Hamster Player Class
A demonstration of extending the Arcade Physics Sprite class to create a controllable character with encapsulated movement, jumping, and animation logic.
1024 × 768
import ANIMATION_KEYS from "../animationKeys.js";
import SPRITE_KEYS from "../spriteKeys.js";
export class Hamster extends Phaser.Physics.Arcade.Sprite
{
jumpVelocity = -520;
constructor (scene, x, y)
{
super(scene, x, y, SPRITE_KEYS.HAMSTER);
scene.add.existing(this);
scene.physics.add.existing(this);
this.setCollideWorldBounds(true);
this.setDepth(100);
}
moveLeft()
{
this.setVelocityX(-160);
this.anims.play(ANIMATION_KEYS.PLAYER_LEFT, true);
}
moveRight()
{
this.setVelocityX(160);
this.anims.play(ANIMATION_KEYS.PLAYER_RIGHT, true);
}
idle()
{
this.setVelocityX(0);
this.anims.play(ANIMATION_KEYS.PLAYER_IDLE);
}
jump()
{
if (this.body.touching.down) this.setVelocityY(this.jumpVelocity);
}
}More in GameObjects13 examples
Key Sprite ClassA custom Sprite class for a collectible item that demonstrates a floating tween animation, cross-scene audio triggering, and self-destruction.Mystery Box Platformer MechanicA custom Arcade Physics Sprite that reacts to being hit from below, triggering a bump animation and spawning an item.Platformer Enemy Edge DetectionA sprite that uses an Arcade Physics sensor to detect the edges of platforms and automatically change direction.Static Physics Sprite ClassDemonstrates creating a custom class that extends an Arcade Physics Sprite to define a static level exit with a specific texture frame and origin.