Being new to phaser I’m having a hard time creating game objects that constist of more than just an image or sprite and are logically grouped together. I’m thinking of something like a prefab in Unity.
Concrete Example; a character consisting of a sprite(sheet) and a health bar with encapsulated logic (taking damage, and so on…) together in one class file (using arcade physics for the sprite), that can then be instantiated on behalf in the scene.
Any example code suggestions for doing something like that would be highly appreciated.
Thank you
Maybe try some approach like this?
/* MainScene */
export default class MainScene extends Phaser.Scene {
constructor() {
super({ key: 'MainScene' })
}
create() {
let dude = new Dude(this, 250, 50)
}
}
/* Dude Class */
class Dude extends Phaser.Physics.Arcade.Sprite {
healthBar
constructor(scene, x = 0, y = 0, texture = 'dude') {
super(scene, x, y, texture)
scene.add.existing(this)
scene.physics.add.existing(this)
scene.events.on('update', this.update, this)
this.healthBar = new HealthBar(scene)
}
update() {
this.healthBar.follow(this)
}
}
/* HealthBar Class */
class HealthBar extends Phaser.GameObjects.Sprite {
constructor(scene, x = 0, y = 0, texture = 'healthBar') {
super(scene, x, y, texture)
scene.add.existing(this)
}
follow(dude) {
this.setX(dude.x)
this.setY(dude.y - 50)
}
}
3 Likes
If you are using TypeScript you could also easily use mixins. Then you could to something like
class Ghost extends Enemy implements Invisible, Magic
Oh yes, this absolutely should get it kicked off! Will take a look at TypeScript, too.
Thank you very much!