The sample snake that comes with the android SDK can only control the direction of the snake through the up and down arrow keys,
There is no problem playing on the simulator. After the phone is installed, it basically won't work. In the spirit of self-improvement, I made some small changes,
The mobile phone screen slides to control the direction,
The main class involved is public gesturedetector (gesturedetector. ongesturelistener listener), which is a touch gesture recognition class,
Some methods in the gesturedetector. ongesturelistener interface need to be implemented in the listener bound listener. Here we mainly implement
Public Boolean onfling (motionevent E1, motionevent E2, float velocityx, float velocityy) Method
Public Boolean onfling (motionevent E1, motionevent E2, float velocityx,
Float velocityy ){
// Todo auto-generated method stub
Log. D ("tag", "onfling ");
System. Out. println ("onfling ");
If (math. Abs (e1.gety ()-e2.gety ()> math. Abs (e1.getx ()-e2.getx () // obtain the absolute value to determine whether the sliding is horizontal or vertical.
{
If (e1.gety ()> e2.gety ())
{
System. Out. println ("up ");
Msnakeview. onkeydown (keyevent. keycode_dpad_up, null );
}
Else
{
System. Out. println ("down ");
Msnakeview. onkeydown (keyevent. keycode_dpad_down, null );
}
}
Else
{
If (e1.getx ()> e2.getx ())
{
System. Out. println ("lef ");
Msnakeview. onkeydown (keyevent. keycode_dpad_left, null );
}
Else if (e1.getx () <e2.getx ())
{
System. Out. println ("right ");
Msnakeview. onkeydown (keyevent. keycode_dpad_right, null );
}
}
Return false;
}
Next, we need to add an ontouchlistener listener on msnakeview, that is, msnakeview. setontouchlistener (ontouchlistener L)
To implement the ontouchlistener interface
Public Boolean ontouch (view V, motionevent event ){
// Todo auto-generated method stub
Return gesturedetector. ontouchevent (event );
}
After the above steps are completed, the basic work is completed. After the software is installed on the mobile phone, the mobile phone still cannot recognize the sliding gesture, which is very distressing. Then I found something missing,
Msnakeview. setlongclickable (true );
This must be added. Otherwise, the onfling method will not be called.