Phaser Box2d-在一个方向上锁定拖动

Phaser Box2d - Lock drag in one direction

本文关键字:方向 一个 锁定 拖动 Box2d- Phaser      更新时间:2023-09-26

我正在开发Phaser的Box2d插件来构建一个游戏。在游戏中,可以用鼠标拖动物体。但我想固定拖动方向,即对象应该只在水平或垂直方向上移动。

我已经查看了官方的例子和文档。找不到符合目的的东西。

此示例显示了使用sprite.input.allowVerticalDrag = false的运动方向锁定,但它不适用于Box2d的拖动。

我按照这个例子来启用拖动。我已经尝试在mouseDragMoveupdate函数中将sprite.body.y设置为类似300的固定值,以便它确实在y方向上移动。但结果并不顺利。它仍然朝那个方向有点摇晃。

我能做些什么来实现这一点?我是否缺少插件的任何内置选项?

我找到了一个解决方案。我所做的是在传递给框架的mouseDragMove处理程序的mousePointer参数中覆盖特定轴上的sprite位置。

以下是它的工作原理-

var isDragging = false,
activeSpriteX=0,
activeSpriteY=0;
function mouseDragStart(e) {
    isDragging = true;
    //get the clicked sprite
    var currentSprite = game.physics.box2d.getBodiesAtPoint(e.x, e.y);
    //save the position of clicked sprite
    if (currentSprite.length > 0) {
        activeSpriteX = game.input.mousePointer.x;
        activeSpriteY = game.input.mousePointer.y;
    }
    game.physics.box2d.mouseDragStart(game.input.mousePointer);
}
function mouseDragMove() {
    mousePointer = game.input.mousePointer;
    //if sprite is being dragged
    if (isDragging) {
        //HERE IS THE WHOLE TRICK - 
        //just override the vertical position of `mousePointer` to sprite's initial position, when it was clicked
        //To fix the sprite in horizontal direction, just override the `x`
        mousePointer.y = activeCarY;
    }
    game.physics.box2d.mouseDragMove(mousePointer);
}
function mouseDragEnd(e) {
    game.physics.box2d.mouseDragEnd();
    isDragging = false;
}

我们在制作的一款游戏中遇到了类似的问题,尽管我们的游戏不使用物理,但我们所做的可能对您有用。整个想法是在拖动对象时使用tweens来设置对象的位置(而不是直接设置其位置)-这样,您就可以在执行tween时手动运行检查和设置约束,如果您的输入位于对象不应该位于的位置,则只需不将tween执行到该位置即可。