如何使用Rect.intersect方法.

Koh*_*yer 5 android canvas intersect

我创建了一个游戏,你可以移动一个矩形并从天空中躲避其他下降的矩形.虽然每次矩形相交都没有任何反应.

if(mSquare.intersect(jSquare)){ canvas.drawColor(Color.BLACK);
要么

collision = mSquare.intersect(jSquare);
     if(collision==true){  canvas.drawColor(Color.RED);
  }  this always returns false no matter where the rectangles are....... 
Run Code Online (Sandbox Code Playgroud)

sla*_*ton 5

有很多方法可以做到这一点,最简单的方法是获取每个时间步的边界RectBitmap以使用Rect.intersect()方法检查碰撞。

像这样的东西:

boolean collision = player.getRect().intersect(fallingObject.getRect());
Run Code Online (Sandbox Code Playgroud)

此外,还有许多其他(更好的)方法可以做到这一点,尤其是在处理不是矩形的对象以及屏幕上有很多对象时。看看这篇文章,进行一个很好的讨论

此外,“Beginning Android Games”一书有一个关于碰撞检测的精彩章节,如果您正在考虑编写游戏,这本书非常值得一读。