タッチ操作でキャラを斜め移動させたくない時
ドラクエや迷路ゲームで、自キャラを斜め移動させたくない時のタッチパネル操作実装例。
タッチ操作時の指の移動のX移動量とY移動量を、”絶対値で”比較するのがミソ。
ただ、これは処理のベースが前回のタッチした画面の座標と今回のタッチした画面の座標を比較して算出することに依存していることに注意。
// タッチパネル操作 -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { lastPoint = [[touches anyObject] locationInView:self.superview]; } -(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { // タッチした座標を取得 CGPoint p=[[touches anyObject] locationInView:self.superview]; // タッチ操作量はX方向とY方向のどちらが多いか絶対値で比較する(lastPointとpの座標を取得する構造がゆえに) float temp_vx, temp_vy; temp_vx=abs(lastPoint.x-p.x); temp_vy=abs(lastPoint.y-p.y); if (temp_vx > temp_vy) { if (lastPoint.x-p.x<0) { vx=1.0f; vy=0.0f; //斜め移動防止。以下同様 } else { vx=-1.0f; vy=0.0f; } } else { if (lastPoint.y-p.y<0) { vy=1.0f; vx=0.0f; } else { vy=-1.0f; vx=0.0f; } } // さっき取得したタッチの座標をラストポイントに書き換えておく。 lastPoint = p; } -(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { } -(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { [self touchesEnded:touches withEvent:event]; }