简单的碰撞检测 - 的Andr​​oid [英] Simple Collision Detection - Android

查看:125
本文介绍了简单的碰撞检测 - 的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做非常简单的碰撞检测像游戏中的乒乓球。
这个球是一个正方形和桨(蝙蝠)是矩形。

I want to do really simple collision detection in a pong like game. The ball is a square and the paddle (bats) is rectangles.

我有两个实体,在那里我可以得到当前的X和Y位置,位图的高度和宽度来了。这是最简单的方法是什么?

I have two entities coming in where I can get the current X and Y position, and the bitmap height and width. Which is the simplest way to do this?

我有这样的code:

public void getCollision(Entity enitityOne, Entity enitityTwo){

    double eventCoordX = (enitityOne.getCenterX() - (enitityTwo.getBitmapWidth() / 2));
    double eventCoordY = (enitityOne.getCenterY() - (enitityTwo.getBitmapHeight() / 2));

    double X = Math.abs(enitityTwo.getxPos() - eventCoordX);
    double Y = Math.abs(enitityTwo.getyPos() - eventCoordY);

    if(X <= (enitityTwo.getBitmapWidth()) && Y <= (enitityTwo.getBitmapHeight())){
        enitityOne.collision();
        enitityTwo.collision();
    }
}

但我pretty盲目的,在没有桨的两侧的中间这只作品。
问题是我不能看到那里的code是错误的。
任何人?
任何人有一个更好的主意?

But I'm pretty blind, this only works in the middle of the paddle not on the sides. The problem is I can't see where the code is wrong. Anybody? Anybody have a better idea?

推荐答案

如果你想要的是找到2中给出的矩形是否不以某种方式相交(因而碰撞),这里是最简单的检查(C code;感觉可以自由使用浮点值):

If all you want is to find whether or not 2 given rectangles somehow intersect (and therefore collide), here's the simplest check (C code; feel free to use floating-point values):

int RectsIntersect(int AMinX, int AMinY, int AMaxX, int AMaxY,
                   int BMinX, int BMinY, int BMaxX, int BMaxY)
{
    assert(AMinX < AMaxX);
    assert(AMinY < AMaxY);
    assert(BMinX < BMaxX);
    assert(BMinY < BMaxY);

    if ((AMaxX < BMinX) || // A is to the left of B
        (BMaxX < AMinX) || // B is to the left of A
        (AMaxY < BMinY) || // A is above B
        (BMaxY < AMinY))   // B is above A
    {
        return 0; // A and B don't intersect
    }

    return 1; // A and B intersect
}

的矩形A和B是由最小和最大X定义及其四角的Y坐标。

The rectangles A and B are defined by the minimum and maximum X and Y coordinates of their corners.

呃...... 这已经被问之前。

Um... This has been asked before.

这篇关于简单的碰撞检测 - 的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆