我正在使用Android Studio 2.3.2在Android上编写Snake编程
为了移动蛇我已经制作了一个onTouchListener来检测用户是否正在滑动以及朝哪个方向(北,南,东,西)
以下是View.onTouchListener的onTouch方法:
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prevX = event.getX();
prevY = event.getY();
break;
case MotionEvent.ACTION_UP:
float newX = event.getX();
float newY = event.getY();
//Calculates where we swiped
if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
//LEFT - RiGHT Direction
if( newX > prevX) {
//RIGHT
gameEngine.updateDirection(Direction.East);
} else {
//LEFT
gameEngine.updateDirection(Direction.West);
}
} else {
// UP-DOWN Direction
if (newY > prevY) {
//DOWN
gameEngine.updateDirection(Direction.South);
} else {
//UP
gameEngine.updateDirection(Direction.North);
}
}
break;
}
return false;
}
问题在于它只检测LEFT和RIGHT(所以EAST和WEST)。 我不知道为什么UP和DOWN没有被检测到。
答案 0 :(得分:1)
尝试以下代码。它对我有用。
爪哇:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class MainSnake extends AppCompatActivity implements View.OnTouchListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_snake);
findViewById(R.id.main_view).setOnTouchListener(this);
}
float prevX, prevY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prevX = event.getX();
prevY = event.getY();
return true;
case MotionEvent.ACTION_UP:
float newX = event.getX();
float newY = event.getY();
//Calculates where we swiped
if (Math.abs(newX - prevX) > Math.abs(newY - prevY)) {
//LEFT - RiGHT Direction
if( newX > prevX) {
//RIGHT
Log.i("TOUCH INFO", "Right");
} else {
//LEFT
Log.i("TOUCH INFO", "Left");
}
} else {
// UP-DOWN Direction
if (newY > prevY) {
//DOWN
Log.i("TOUCH INFO", "Down");
} else {
//UP
Log.i("TOUCH INFO", "Up");
}
}
break;
}
return false;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_view">
</android.support.constraint.ConstraintLayout>
答案 1 :(得分:0)
您必须返回&#34; True&#34;在ACTION_DOWN之后。这告诉Android要注意ACTION_UP事件。
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
prevX = event.getX();
prevY = event.getY();
return true;