Phaser 3:立即单击并拖动克隆 Sprite

Phaser 3: Clone Sprite on click & drag immediately

我有一个用作按钮的 sprite,但当您按下它时,它会复制并让您拖动副本。我几乎已经开始工作了,但是目前您必须先单击才能创建副本,并且只能在第二次单击后进行拖动。我希望能够单击一次并立即能够拖动。

重要的是拖动复制品,而不是原始文件,因为原始文件具有所有点击功能。

create() {
    sprite = scene.add.sprite(0,0, "clean", "showerhead_0000");
    sprite.setInteractive({ useHandCursor: true });
    sprite.on('pointerdown', () => {
                dragTool(scene, options[idx], sprite);
    });

    this.input.on('drag', function(pointer, gameObject, dragX, dragY) {
        gameObject.x = dragX;
        gameObject.y = dragY;
    });
    
    this.input.on('dragend', function(pointer, gameObject) {
        gameObject.destroy();
        gameState.clean_cursor = false;
    });
}

function dragTool(scene, option, sprite){
    let activePointer = scene.input.activePointer;
    let clone = scene.add.sprite(sprite.x,sprite.y, sprite.texture.key, sprite.frame.name);
    gameState.clean_cursor = clone;

    gameState.clean_cursor.setInteractive();
    scene.input.setDraggable(gameState.clean_cursor);
}

也许我遗漏了什么,但一个简单的解决方案是。

  1. 创建两个 images/buttons,一个正常,一个作为占位符
    • 占位符会被原来的覆盖,拖动时除外
  2. 拖动时,只需拖动普通按钮
  3. 拖动结束时重置普通按钮的位置

这应该是一样的,而且没有那么复杂。

这是一个工作示例:

let Example = {
    preload () {
        this.load.spritesheet('brawler', 'https://labs.phaser.io/assets/animations/brawler48x48.png', { frameWidth: 48, frameHeight: 48 });
    },
    create () {
        let buttonPos = { x:0, y:0};
        let buttonPlaceholder = this.add.image(buttonPos.x, buttonPos.y, 'brawler', ).setOrigin(0, 0);
        let button = this.add.image(buttonPos.x, buttonPos.y, 'brawler', ).setOrigin(0, 0);
       
        this.isDragging = false;

        button.setInteractive({ useHandCursor: true });
        this.input.setDraggable(button);

        this.input.on('drag', function(pointer, gameObject, dragX, dragY) {
            gameObject.x = dragX;
            gameObject.y = dragY;
        });
        
        this.input.on('dragend', function(pointer, gameObject) {
            gameObject.x = buttonPos.x;
            gameObject.y = buttonPos.y;
        });
    }
}

const config = {
    type: Phaser.AUTO,
    width: 400,
    height: 200,
    scene: [ Example ]
};

const game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

...这应该比创建和销毁 image/buttons...

更高效