当有人使用onTouchEvent(MotionEvent)点击屏幕时,试图让我的精灵跳跃,但不知道应该如何使用这种方法?



现在我的游戏中只有一个从屏幕左侧移动到右侧的精灵。我试图让它在触摸屏幕时跳跃,所以我添加了这个类:

 import android.app.Activity;
 import android.view.MotionEvent;
 public class TouchScreen extends Activity {
 private Player p;
 public boolean onTouchEvent(MotionEvent e) {
    int i = e.getAction();
    switch (i) {
    case MotionEvent.ACTION_DOWN:
        // When your finger touches the screen
        p.jump();
        break;
    case MotionEvent.ACTION_UP:
        // When your finger stop touching the screen
        break;
    case MotionEvent.ACTION_MOVE:
        // When your finger moves around the screen
        break;
    }
    return false;
    }
  }    

现在我正试图在Player.update()中调用这个方法(Player是sprite的类),但我不知道该向onTouchEvent()传递什么。我基本上想要"如果屏幕被点击,让玩家跳跃"(通过调用Player.jump()),有什么想法吗?

您需要指定onTouchEvent覆盖Activity中的原始方法。您还应该在最后调用super.onTouchEvent(e);,因为您正在重写的方法可能需要执行。

@Overrides
public boolean onTouchEvent(MotionEvent e) {
int i = e.getAction();
switch (i) {
case MotionEvent.ACTION_DOWN:
    // When your finger touches the screen
    p.jump();
    break;
case MotionEvent.ACTION_UP:
    // When your finger stop touching the screen
    break;
case MotionEvent.ACTION_MOVE:
    // When your finger moves around the screen
    break;
}
return super.onTouchEvent(e);
}

您没有显式调用onTouchEvent,这应该在活动被触摸时由系统调用。不过你已经把p.jump();放在了正确的位置!

最新更新