我有一个火箭着陆游戏,玩家是火箭,你必须将其以正确的速度安全地降落在着陆垫上。这是取自 www.gametutorial.net
这实际上是出于教育目的,我最近在游戏中添加了一颗静止的 meteor 。 当玩家击中 meteor (触摸)时,游戏结束。
if(...) {
playerRocket.crashed = true;
}
我的问题是我需要将“...”替换为实际情况“火箭是否撞上了 meteor ?”
加上以下变量(坐标、高度和宽度)以供使用 - [所有整数]:
X and Y coordinates: playerRocket.x, playerRocket.y, meteor.x, meteor.y
Height and Width: playerRocket.rocketImgHeight, playerRocket.rocketImgWidth, meteor.meteorImgHeight, meteor.meteorImgWidth
最佳答案
对于 2D 游戏中的碰撞检测,您可以使用矩形。我将使用一个名为 GObject
的基类,并从中继承游戏中的所有对象。
public class GObject
{
private Rectangle bounds;
public float x, y, hspeed, vspeed;
private Image image;
public GObject(Image img, float startx, float starty)
{
image = img;
x = startx;
y = starty;
hspeed = vspeed = 0;
bounds = new Rectangle(x, y, img.getWidth(null), img.getHeight(null));
}
public Rectangle getBounds()
{
bounds.x = x;
bounds.y = y;
return bounds;
}
}
还有其他方法,例如 update()
和 render()
,但我没有展示它们。因此,要检查两个对象之间的碰撞,请使用
public boolean checkCollision(GObject obj1, GObject obj2)
{
return obj1.getBounds().intersects(obj2.getBounds());
}
此外,还有一个专门针对游戏相关问题的网站。前往Game Development Stack Exchange
关于Java 2D 游戏 - 检查玩家是否触摸另一个 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17269705/