Sasha McCarn
Sasha McCarn

Reputation: 41

Check collisions between two objects in java

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

Upvotes: 1

Views: 3115

Answers (3)

subsub
subsub

Reputation: 1857

item is not made null unless i specifically say so in the panel.

Why should it be otherwise? i = null; just sets the local variable i to null.

Upvotes: 1

Swaranga Sarma
Swaranga Sarma

Reputation: 13413

The Javadoc for Rectangle clearly suggests that if the intersection is non zero then rectangle.intersects() return true otherwise false.

Could it be possible that your item.getBounds() and getBounds() methods are returning bounds relative to different bounding components?

Upvotes: 2

jberg
jberg

Reputation: 4818

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?

Upvotes: 0

Related Questions