这两天一直在纠结。我正在使用一个名为 ImpactJS 的 HTML5/JS 游戏引擎,有人制作了一个非常有用的插件来为移动设备创建操纵杆触摸区域。这个想法是您在屏幕上指定一个区域,当该区域被触摸时,操纵杆将被激活。
我使用的插件代码是here .我稍微修改了它以添加“curPos”(用户当前触摸的点的 x 和 y 坐标),否则所有代码都是相同的。我一直在尝试自己解决这个问题并联系原作者,但此时他们似乎无法联系上,我无处可去。
我确定我在这里做错了什么,但是虽然我可以让触摸区域自己完美地工作,但每次我尝试同时使用两个操纵杆时它们都会部分地相互覆盖。
我在游戏初始化时指定了如下两个区域:
this.joystick1 = new TouchJoystickZone(0, 0, ig.system.width / 2, ig.system.height);
this.joystick2 = new TouchJoystickZone(ig.system.width / 2, 0, ig.system.width / 2, ig.system.height);
this.joystick1 负责玩家旋转。 this.joystick2 负责玩家加速。在我的 Player 实体中,我有以下两个操纵杆的移动代码。同样,当我只有一根手指在屏幕上/使用一个操纵杆时,这非常有效:
if( ig.ua.mobile ) {
// ROTATION
if (ig.game.joystick1.touchStart.x > 0 && ig.game.joystick1.touchStart.x < ig.system.width/2) {
if (Math.abs(ig.game.joystick1.delta.x) >= 50 || Math.abs(ig.game.joystick1.delta.y) >= 50) {
this.joystickAngle = ig.game.Controller.toDegrees(ig.game.Controller.joystickAngle());
if (this.angle > this.joystickAngle + 20) {
this.angle -= this.turnSpeed * ig.system.tick;
}
else if (this.angle < this.joystickAngle - 20) {
this.angle += this.turnSpeed * ig.system.tick;
}
else {
this.angle = this.joystickAngle;
}
}
}
// THRUST
if (ig.game.joystick2.touchStart.x > ig.system.width / 2) {
if (ig.game.joystick2.delta.y <= -50) {
this.accel.x = Math.cos(this.angle*Math.PI/180)*this.thrust;
this.accel.y = (Math.sin(this.angle*Math.PI/180)*this.thrust);
this.fuel -= 0.1;
}
else if (ig.game.joystick2.delta.y >= 50) {
this.accel.x = Math.cos(this.angle*Math.PI/180)*-this.thrust;
this.accel.y = (Math.sin(this.angle*Math.PI/180)*-this.thrust);
this.fuel -= 0.1;
}
}
else {
this.accel.x = 0;
this.accel.y = 0;
}
}
然而,一旦我将第二根手指放在屏幕上,第一个操纵杆就会被覆盖。我可以旋转然后移动或移动然后旋转并且它工作正常,但我需要同时进行这两项操作。
我发现当我点击使用另一个摇杆而不仅仅是相关的 joystick1 或 joystick2 时,似乎为两个操纵杆设置了 touchStart.x 和 touchStart.y,即使在插件代码中这些坐标只是意味着如果该操纵杆的触摸在指定区域内,则会受到影响。我相信这是导致该问题的部分原因。在这个阶段,我花了几个小时试图弄清楚这一点,但和刚开始时一样迷茫。
有人可以同时使用这两个操纵杆为我指出正确的方向吗?
最佳答案
您正在使用的操纵杆脚本只寻找第一个手指。以下来自第47-48行
var x = ev.touches[0].pageX - pos.left,
y = ev.touches[0].pageY - pos.top;
“0”决定跟踪哪个手指。
脚本将被更改为知道哪个手指在哪个元素上,然后仅跟踪该手指。您可以通过确定先按下哪个元素或按位置来做到这一点。
JSFiddle 示例:http://jsfiddle.net/7WR88/5/
http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/
关于javascript - 尝试让两个同时操纵杆处理触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029691/