迷路ゲーム、タッチ操作でスムーズ移動
以下の仕様を満たすようにしました。(イメージは添付画像参考)
■親指ひとつでキャラを操作
■一度入力した方向に移動し続ける
■画面のどこでもタッチ操作(バーチャルコントローラーではない)
■カベで止まる
■キャラは32pixel x 32pixel
ポイントは、タッチ操作のときに方向を記憶する変数を用意しておくこと。
それによって、カベで移動できなくともプレイヤーが操作したい方向を記憶している(先読み)ので、スムーズな移動ができる。
注)パックマンの移動と似ているが、カベで止まる仕様が異なる
- (void)drawRect:(CGRect)rect { // いろいろ省略 // タッチ操作の方向に応じて移動量を代入しておく。 // touch_directionはhファイルで定義しておく。 int touch_direction; if (touch_direction==1) vy=-1.0f; if (touch_direction==2) vx= 1.0f; if (touch_direction==3) vy= 1.0f; if (touch_direction==4) vx=-1.0f; // カベ判定 // x if (vx>0) { mx =(px+31.0f+vx)/32.0f; my =py/32.0f; my2=(py+31.0f)/32.0f; if (MAP[(int)my ][(int)mx]==1) vx=0.0f; if (MAP[(int)my2][(int)mx]==1) vx=0.0f; } else { mx =(px+vx)/32.0f; my =py/32.0f; my2=(py+31.0f)/32.0f; if (MAP[(int)my ][(int)mx]==1) vx=0.0f; if (MAP[(int)my2][(int)mx]==1) vx=0.0f; } px=px+vx; // y if (vy>0) { mx =px/32.0f; mx2=(px+31.0f)/32.0f; my =(py+31.0f+vy)/32.0f; if (MAP[(int)my][(int)mx ]==1) vy=0.0f; if (MAP[(int)my][(int)mx2]==1) vy=0.0f; } else { mx =px/32.0f; mx2=(px+31.0f)/32.0f; my =(py+vy)/32.0f; if (MAP[(int)my][(int)mx ]==1) vy=0.0f; if (MAP[(int)my][(int)mx2]==1) vy=0.0f; } py=py+vy; } // タッチパネル操作 -(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) { touch_direction=2; } else { touch_direction=4; } } else { if (lastPoint.y-p.y<0) { touch_direction=3; } else { touch_direction=1; } } // さっき取得したタッチの座標をラストポイントに書き換えておく。 lastPoint = p; }