检查java中两个对象之间的碰撞
我有一个方法可以检查玩家和物品是否相交并将物品添加到库存中,但该方法似乎只有在矩形完全重叠的情况下才有效,并且除非我在控制板。否则,该项目会在面板上不断移动,就好像什么也没发生一样。
public boolean obtainItem(Item item)
{
if (item.moveable)
{
Rectangle p = getBounds();
Rectangle i = item.getBounds();
if (p.intersects(i))
{
inventory.add(item);
i = null;
System.out.println("hello");
return true;
}
}
return false;
}
我的 getBounds() 方法的代码是
public Rectangle getBounds() { 边界 = 新矩形(x, y, 40, 40); 返回边界; 它
返回正确的边界
I have a method that checks if the player and the item are intersecting and adds the item to the inventory, but the method only seems to work if the rectangles are completely overlapping, and the item is not made null unless i specifically say so in the panel. Otherwise, the item keeps moving around the panel as if nothing happened.
public boolean obtainItem(Item item)
{
if (item.moveable)
{
Rectangle p = getBounds();
Rectangle i = item.getBounds();
if (p.intersects(i))
{
inventory.add(item);
i = null;
System.out.println("hello");
return true;
}
}
return false;
}
The code for my getBounds() methods are
public Rectangle getBounds()
{
bounds = new Rectangle(x, y, 40, 40);
return bounds;
}
And it is returning the correct bounds
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
矩形的 Javadoc 很清楚建议如果交集非零,则
rectangle.intersects()
返回true
,否则false
。您的
item.getBounds()
和getBounds()
方法是否有可能返回相对于不同边界组件的边界?The Javadoc for Rectangle clearly suggests that if the intersection is non zero then
rectangle.intersects()
returntrue
otherwisefalse
.Could it be possible that your
item.getBounds()
andgetBounds()
methods are returning bounds relative to different bounding components?为什么要不然呢?
i = null;
只是将局部变量 i 设置为 null。Why should it be otherwise?
i = null;
just sets the local variable i to null.所有这些代码看起来都很好,假设您使用 java.awt.Rectangle 正如 iluxa 指出的那样。这很可能是您的 Item 类中的错误。你能发布那个吗?
All of that code looks fine, assuming you are using java.awt.Rectangle as iluxa pointed out. It is most likely an error in your Item class. Can you post that?