Phaser 3.70.0 drggable container like modal

class DraggableContainer extends Phaser.GameObjects.Container {

  constructor(
    scene,
    x,
    y,
    width,
    height,
    children) {
    super(scene, x, y, children)

    scene.add.existing(this)

    this.setSize(width, height)
      .setInteractive()
      .on('drag', (pointer) => {
        this.setX(pointer.x - this._dragX + width / 2)
        this.setY(pointer.y - this._dragY + height / 2)
      })
      .on('pointerdown', (pointer, x, y) => {
        this._dragX = x
        this._dragY = y
      })

    scene.input.setDraggable(this, true)
  }
}




class Example extends Phaser.Scene
{
    constructor()
    {
        super();
    }

    preload ()
    {
        this.load.image('bg', 'assets/skies/gradient13.png');
        this.load.atlas('rocket', 'assets/animations/rocket.png', 'assets/animations/rocket.json');
    }

    create ()
    {
        this.add.image(400, 300, 'bg');
        this.add.text(16, 16, 'Drag the Rocket').setFontSize(24).setShadow(1, 1);

        this.anims.create({ key: 'trail', frames: this.anims.generateFrameNames('rocket', { prefix: 'trail_', start: 0, end: 12, zeroPad: 2 }), repeat: -1 });

        const container = this.add.container(400, 300);

        //  A container must have a size in order to receive input
        container.setSize(120, 80);
        container.setInteractive({ draggable: true });

        const trail = this.add.sprite(-125, 0).play('trail');
        const rocket = this.add.sprite(0, 0, 'rocket', 'rocket');

        container.add([ trail, rocket ]);

        container.on('drag', (pointer, dragX, dragY) => container.setPosition(dragX, dragY));

        let rect1 = this.add.rectangle(0, 0, 120, 40, 0xff00ff)
    let rect2 = this.add.rectangle(0, 40, 120, 40, 0xffff00)
    let text = this.add.text(0, 0, 'some-text', { color: 'black' }).setOrigin(.5)
    let container1 = new DraggableContainer(this, 250, 250, 120, 80, [rect1, rect2, text])

    }
}

const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    parent: 'phaser-example',
    scene: Example
};

const game = new Phaser.Game(config);

Lets see it working

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>