HTML5 移动游戏开发技巧与优化策略
1. 触摸事件处理
在 HTML5 移动游戏开发中,触摸事件的处理至关重要。以下是一段处理触摸事件的代码示例:
if (phy) {
touchId = touch.identifier;
isDown = phy.collide
(touch[touchId].pageX, touch[touchId].pageY, 0, 0);
}
// Clear the touch flag on the entity, as well as the touch id
function doOnTouchUp(event) {
event.preventDefault();
isDown = false;
touchId = 0;
}
// Always move the entity based on the cached touch id
function doOnTouchMove(event) {
event.preventDefault();
var touch = event.changedTouches;
if (isDown) {
pos.x = touch[touchId].pageX;
pos.y = touch[touchId].pageY;
}
}
通过跟踪原始触摸并仅对其做出响应,即使屏幕上同时发起多个触摸,也能保证触摸输入的准确性。这也是实现手势或其他基于任意触摸组合的输入触发器时,跟踪不同触摸的正确方法。