2011-11-18 75 views
0

我已經發布了一個關於此主題的問題..但沒有得到答案。我正在做一個遊戲。在那個應用程序中,我必須檢測畫布中兩個對象的碰撞。對象類粘貼在這裏。Android中兩個對象的碰撞檢測

 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個移動物體與用戶控制對象發生碰撞的事件。我已經閱讀了許多教程,但還沒有得到解決方案。請幫助我的人...

+0

沒有人爲此問題提供答案?????? :( –

+0

使用AndEngine進行遊戲會更好。 –

回答

0

您應該使用一個庫,提供檢測精靈碰撞的功能。嘗試谷歌搜索「android精靈碰撞」。

1

在一般情況下,通過使用不精確表示簡化碰撞檢測通常是一個好主意,因爲它是易於使用和實施,以及速度一般很好。對於這樣的解決方案,使用軸對齊邊界框或可能的圓圈進行碰撞檢測應該可以正常工作。對於更復雜的解決方案,基於多邊形的解決方案是可用的,但它們更難以使用。

如果您需要更精確的碰撞檢測,例如檢測兩幅圖像之間的碰撞,則需要像素完美的碰撞檢測。這通常很難有效地進行,因此建議使用現有的庫。

由於您使用Java,並且您似乎使用位圖,AndEngine作爲Reno建議或PoxelColl應該做的伎倆。如果你需要旋轉和縮放等基本轉換,我推薦PoxelColl。