Search code examples
javascriptbox2dgame-physicsdragphaser-framework

Phaser Box2d - Lock drag in one direction


I am working on Phaser's Box2d plugin to build a game. In the game, objects can be dragged around with mouse. But I want to fix the drag direction i.e. object should move only horizontal or vertical direction.

I have checked official examples and docs. Couldn't find anything which serves the purpose.

This example shows the motion direction lock using sprite.input.allowVerticalDrag = false, but it is doesn't work with Box2d's drag.

I am following this example to enable the drag. I have tried setting sprite.body.y to a fix value like 300 in both mouseDragMove and update functions, so that it does move in y direction. But results are not smooth. It still shakes a little bit in that direction.

What can I do implement this? Am I missing any built-in option of the plugin?


Solution

  • I was able to figure out a solution for it. What I did is to override the sprite position, in a particular axis, in mousePointer parameter that is passed to mouseDragMove handler of the framework.

    Here is how it works -

    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;
    }