===== タッチ操作、スライドした分だけキャラクターを移動する ======
タッチ操作でスライドした分だけキャラクターを移動する処理を作成します。
まず、タッチ情報は以下のようにして取得できます。(参考: [[https://qiita.com/minimo/items/fd8ed4a0ccecd33509ac|phina.jsでマルチにタッチ - Qiita]])
var p = app.pointers;
for (var i = 0; i < p.length; i++) {
p[i].x; // x座標
p[i].y; // y座標
p[i].id; // タッチID
}
スライド量に応じてキャラクターを動かすために、前回のタッチ位置を記憶しておいて、今回のタッチ位置との差に応じてキャラを移動します。
マルチタッチで他の指と間違わないようにタッチIDが一致しているものを対象に処理します。
if (this.touch.id == touches[i].id) {
this.player.x += (touches[i].x - this.touch.x) * this.player.SPEED_BY_TOUCH;
this.player.y += (touches[i].y - this.touch.y) * this.player.SPEED_BY_TOUCH;
this.touch.x = touches[i].x;
this.touch.y = touches[i].y;
}
一致するIDが見つからなかった場合は指が離されたものとして前回タッチ位置の情報を初期化します。
あと、マウスの操作もタッチ情報として入力されてしまうため、マウスイベントが入ってきた場合にはフラグを立ててスライド操作は行わないようにします。(参考: [[https://lab.syncer.jp/Web/JavaScript/Snippet/44/|JavaScriptでマウスデバイスとタッチデバイスを判別する方法]])
var isMouseUsed = false;
function detectDeviceType(event) {
isMouseUsed = !event.changedTouches;
console.log('isMouseUsed=' + isMouseUsed);
document.removeEventListener('touchstart', detectDeviceType);
document.removeEventListener('mousemove', detectDeviceType);
}
document.addEventListener('touchstart', detectDeviceType);
document.addEventListener('mousemove', detectDeviceType);
まとめると以下のような感じです。
var touches = app.pointers;
var sliding = false;
for (var i = 0; i < touches.length; i++) {
// マウスが接続されていない場合はスライドの処理を行う。
if (!isMouseUsed) {
// スライド操作をしていない状態だった場合、最初のタッチ位置を記憶する。
if (this.touch.id < 0) {
this.touch.id = touches[i].id;
this.touch.x = touches[i].x;
this.touch.y = touches[i].y;
sliding = true;
continue;
}
// スライド操作をしている場合はスライド量に応じて自機を移動する。
if (this.touch.id == touches[i].id) {
this.player.x += (touches[i].x - this.touch.x) * this.player.SPEED_BY_TOUCH;
this.player.y += (touches[i].y - this.touch.y) * this.player.SPEED_BY_TOUCH;
this.touch.x = touches[i].x;
this.touch.y = touches[i].y;
sliding = true;
continue;
}
}
}
// スライドしていない場合はタッチ情報を初期化する。
if (!sliding) {
this.touch.id = -1;
this.touch.x = 0;
this.touch.y = 0;
}