我正在研究Phaser's Box2d用于构建游戏的插件。游戏中,可以用鼠标拖动物体。但我想修复拖动方向,即对象应该仅水平或垂直方向移动。
我已经检查了官方示例和文档。找不到任何可以达到目的的东西。
This example使用 sprite.input.allowVerticalDrag = false
显示运动方向锁定,但它不适用于 Box2d 的拖动。
我正在关注this example启用拖动。我尝试在 mouseDragMove
和 update
函数中将 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;
}
关于javascript - Phaser Box2d - 锁定一个方向的拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34237597/