Android - 复古壁球游戏 - 球拍/屏幕两侧碰撞

时间:2016-03-30 22:27:11

标签: java android collision-detection

我正在阅读“通过构建Android游戏来学习Java”,并且在一个Retro Squash Game示例中,我不知道如何为球拍实现碰撞检测。球拍的运动使用onTouchEvent。我试图实现一个if语句,但是在下一次触摸事件之前它不会被检查 - 所以它不能正常工作。请帮忙。

    //Event that handles in which direction is the racket moving according to where is the user touching the screen
    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        //gets the movement action without the pointers(ACTION_MASK) ??? -U: handles multitouch

        switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
            //what happens if user touches the screen and holds
            case MotionEvent.ACTION_DOWN:
                //if the screen was touched on the right side of the display than move the racket right
                if (motionEvent.getX() >= (screenWidth / 2) && racketPosition.x <= screenWidth) {
                    racketIsMovingLeft = false;
                    racketIsMovingRight = true;
                } else if (motionEvent.getX() < (screenWidth / 2) && racketPosition.x >= 0) {
                    racketIsMovingLeft = true;
                    racketIsMovingRight = false;
                } else {
                    racketIsMovingLeft = false;
                    racketIsMovingRight = false;
                }

                break;
            //when the user lets go of the screen the racket immediately stops moving
            case MotionEvent.ACTION_UP:
                racketIsMovingLeft = false;
                racketIsMovingRight = false;
                break;
        }
        return true;
    }

1 个答案:

答案 0 :(得分:0)

确定。我找到了解决方案。我没有看到正确的代码 - 对不起。我编辑了负责更改球拍的racketPoint.x的部分。这是:

    public void updateCount() {
        //change the racket position according to the movement
        if (racketIsMovingRight && (racketPosition.x+racketWidth/2)<=screenWidth) {
            racketPosition.x += racketSpeed;
        }

        if (racketIsMovingLeft && (racketPosition.x-racketWidth/2)>=0) {
            racketPosition.x -= racketSpeed;
        }

//代码的其余部分