Phaser 3:点击并立即拖动克隆精灵

我有一个像按钮一样工作的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. 创建两个图像/按钮,一个是普通图像/按钮,一个是占位符
    • 占位符将被原始占位符覆盖,但拖动占位符时除外
  2. 拖动时,只需拖动普通按钮
  3. 拖动结束时重置正常按钮的位置

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

这里有一个工作示例:

数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
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>

...这应该比创建和销毁图像/按钮更有性能...

相关文章