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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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