Jump to content

Simple Sprite Button Example


John Difool
 Share

Recommended Posts

I'm a complete newbie to Phaser 3 and I've been trying to learn by doing. I have some difficulties understanding the sprite parent-child hierarchy. 

1. Does the coordinates system get inherited by the children of a parent sprite (new coordinates relative to parent's?)

2. Is sprite hierarchy the way to go if I want to move sprites in group? What does the group do beside letting you enumerate families of sprites? It seems that it's not serving any other purpose in Phaser 3.

Here is a simple (non working) code to help me understand. What I want to achieve is drawing a solid rectangle and placing some text on top, packaging the whole thing into a sprite so I can use it with some variations. The text should be centered inside its parent rectangle. I've looked thru the basic examples, but couldn't find guidance on parent/child relationship. I sincerely appreciate your help.

class GameScene extends Phaser.Scene {

    constructor() {
        super('GameScene');
    }

    preload() {
    }
    create(config) {
        let button = new ButtonNode({
            scene: this,
            key: 'button',
            x: 100,
            y: 100
          });
    }
    update() {
    }
}


class ButtonNode extends Phaser.GameObjects.Sprite {

    constructor(config) {
        super(config.scene, config.x, config.y, config.key);    
        config.scene.add.existing(this);
        this.alive = true;

        let graphics = this.make.graphics();
        graphics.fillStyle(0x0000FF, 1.0);
        graphics.fillRect(200, 200, 50, 50);
        this.addChild(graphics);

        const text = config.scene.make.text({
            scene: config.scene,
            key: 'text',
            x: 10,
            y: 10
          }, 'Hello, Kitty!', { font: '16px Helvetica', fill: '#ffffff' });
        this.addChild(text);
    }
    
}
 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...