2012-08-02 109 views
0

在我的遊戲中,我有矩形ImageView's,從屏幕頂部掉下來。在底部還有另一個可以與加速度計一起移動的ImageViewImageView碰撞

現在我想檢查一下,從頂部落下的ImageView是否與底部的ImageView發生碰撞。我怎樣才能做到這一點?

+0

通過在surfaceview上繪製位圖來做這樣的事情不是更好的辦法嗎?然後碰撞檢測很容易。 – 2012-08-02 12:21:06

+0

sry我不知道這件事。你可以請給我鏈接教程嗎? – Stupe 2012-08-02 12:23:39

+0

這裏是一個:http://www.droidnova.com/playing-with-graphics-in-android-part-ii160.html雖然只是谷歌「android surfaceview教程」,你會發現一百萬其他人。 Youtube視頻太 – 2012-08-02 12:26:41

回答

0

我不太確定你可以碰撞,但仍然可以使用getMeasuredWidth()和Height()來確定你的方形邊界框。然後看看兩個正方形的邊緣是否在相對的邊界框中...

if((square1.x > square2.x && square1.x < square2.x+square2.width) && (square1.y > square2.y && square1.y < square2.y+square2.height)) 
//collision happened 
+0

sry,但是這是爲Android?因爲值'x'和'y'不存在... – Stupe 2012-08-02 12:21:55

0

試試這個。此功能檢測2個ImageViews之間的衝突

public boolean collision(ImageView a, ImageView b){ 
    float bl = a.getY(); 
    float bt = a.getX(); 
    float br = a.getWidth() + bl; 
    float bb = a.getHeight() + bt; 
    float pl = b.getY(); 
    float pt = b.getX(); 
    float pr = b.getWidth() + pl; 
    float pb = b.getHeight() + pt; 
    if (bl <= pr && bl >= pl && bt >= pt && bt <= pb) { 
     return true; 

    } else if (br >= pl && br <= pr && bb >= pt && bb <= pb) { 
     return true; 
    } else if (bt <= pb && bt >= pt && br >= pl && br <= pr) { 
     return true; 
    } else if (bb >= pt && bb <= pb && bl >= pl && bl <= pr) { 
     return true; 
    } 
    return false; 
}