Android中两个对象的碰撞检测

时间:2011-11-18 06:52:49

标签: android collision-detection android-canvas

我已经发布了一个关于这个主题的问题..但是没有得到答案。我正在做一个游戏。在那个app我必须检测画布中两个对象的碰撞。对象类被粘贴在这里。

     public class Droid {

private Bitmap bitmap;  // the actual bitmap
private int x;          // the X coordinate
private int y;          // the Y coordinate
private boolean touched;    // if droid is touched/picked up
private Speed speed;    // the speed with its directions

public Droid(Bitmap bitmap, int x, int y) {
    this.bitmap = bitmap;
    this.x = x;
    this.y = y;
    this.speed = new Speed();
}

public Bitmap getBitmap() {
    return bitmap;
}
public void setBitmap(Bitmap bitmap) {
    this.bitmap = bitmap;
}
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}

public boolean isTouched() {
    return touched;
}

public void setTouched(boolean touched) {
    this.touched = touched;
}

public Speed getSpeed() {
    return speed;
}

public void setSpeed(Speed speed) {
    this.speed = speed;
}


public void draw(Canvas canvas) {
    canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null);
}

/**
 * Method which updates the droid's internal state every tick
 */
public void update() {
    if (!touched) {
        x += (speed.getXv() * speed.getxDirection()); 
        y += (speed.getYv() * speed.getyDirection());
    }
}


/**
 * Handles the {@link MotionEvent.ACTION_DOWN} event. If the event happens on the 
 * bitmap surface then the touched state is set to <code>true</code> otherwise to <code>false</code>
 * @param eventX - the event's X coordinate
 * @param eventY - the event's Y coordinate
 */
public void handleActionDown(int eventX, int eventY) {
    if (eventX >= (x - bitmap.getWidth() / 2) && (eventX <= (x + bitmap.getWidth()/2))) {
        if (eventY >= (y - bitmap.getHeight() / 2) && (y <= (y + bitmap.getHeight() / 2))) {
            // droid touched
            setTouched(true);
        } else {
            setTouched(false);
        }
    } else {
        setTouched(false);
    }

}
}

我正在创建5个droid对象。其中4个在画布上不断移动,1个由用户控制。我想检测这4个移动对象与用户控制对象发生碰撞的事件。我已经阅读了很多教程但还没有得到解决方案。请任何人帮助我......

3 个答案:

答案 0 :(得分:1)

使用AndEngine要简单得多,让它为您简化这些任务。

答案 1 :(得分:1)

通常,通过使用不精确的表示来简化碰撞检测通常是一个好主意,因为它易于使用和实现,并且速度通常很好。对于这样的解决方案,使用轴对齐的边界框或可能的圆圈进行碰撞检测应该可以正常工作。对于更复杂的解决方案,可以使用基于多边形的解决方案,但它们更难使用。

如果您需要更精确的碰撞检测,例如检测两个图像之间的碰撞,则需要像素完美的碰撞检测。这通常很难有效,因此建议使用现有的库。

由于您使用的是Java,并且您似乎使用位图,因此Reno建议使用AndEnginePoxelColl应该可以使用。{3}}。如果您需要旋转和缩放等基本转换,我建议使用PoxelColl。

答案 2 :(得分:0)

您应该使用提供检测精灵冲突功能的库。尝试使用谷歌搜索&#34; android sprite collision&#34;。