位图边界RectF碰撞

时间:2017-12-26 07:09:03

标签: android bitmap collision-detection collision

我一直在尝试创建一个简单的突破式游戏。我有一个球和一个球棒,并且当它与球棒碰撞时想要反转球的方向。蝙蝠由用户的触摸控制,可以在屏幕上自由移动。

@Override
public boolean onTouch(View v, MotionEvent event) {
    x = (int) event.getX();
    y = (int) event.getY();
    return true;
}

在我的游戏循环中:

    int cx = -1;
    int cy = -1;

    private int xVelocity = -11;
    private int yVelocity = -14;

    Bitmap player, ball;
    RectF boundsPlayer, boundsBall;

    float boundCX, boundCY;
    boundCX = (float) cx;
    boundCY = (float) cy;
    player = BitmapFactory.decodeResource(getResources(), R.drawable.nightplayer);
    canvas.drawBitmap(player, x - (player.getWidth() / 2), y - (player.getHeight() + 100), null);

    ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);

    boundsPlayer = new RectF((x - (player.getWidth()/2)), (y - (player.getHeight() + 150)), ((x - (player.getWidth()/2)) + player.getWidth()), ((y - (player.getHeight() + 150)) + player.getHeight()));
    boundsBall = new RectF(boundCX, boundCY, boundCX + ball.getWidth(), boundCY + ball.getHeight());

    if (RectF.intersects(boundsBall, boundsPlayer)) {
                       collision();
    }

private void collision() {
        yVelocity = yVelocity * -1;
        score = score + 1;
        //Log.d(TAG, String.valueOf(score));
        yVelocity = yVelocity - 2;
        if(xVelocity < 0) {
            xVelocity = xVelocity - 2;
        } else if (xVelocity > 0) {
            xVelocity = xVelocity + 2;
        }
        collision = false;
    }

我遇到的问题是,当球与球棒发生碰撞时,它似乎会多次碰撞并反复颠倒方向,而不是“甩掉”球棒。

0 个答案:

没有答案