Search code examples
javacollision-detection

Collision Detection between two images in Java


I have two characters displayed in a game I am writing, the player and the enemy. defined as such:

public void player(Graphics g) {
    g.drawImage(plimg, x, y, this);
}

public void enemy(Graphics g) {
    g.drawImage(enemy, 200, 200, this);
}

Then called with:

player(g);
enemy(g);

I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?


Solution

  • I think your problem is that you are not using good OO design for your player and enemies. Create two classes:

    public class Player
    {
        int X;
        int Y;
        int Width;
        int Height;
    
        // Getters and Setters
    }
    
    public class Enemy
    {
        int X;
        int Y;
        int Width;
        int Height;
    
        // Getters and Setters
    }
    

    Your Player should have X,Y,Width,and Height variables.

    Your enemies should as well.

    In your game loop, do something like this (C#):

    foreach (Enemy e in EnemyCollection)
    {
        Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
        Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);
    
        // Assuming there is an intersect method, otherwise just handcompare the values
        if (r.Intersects(p))
        {
           // A Collision!
           // we know which enemy (e), so we can call e.DoCollision();
           e.DoCollision();
        }
    }
    

    To speed things up, don't bother checking if the enemies coords are offscreen.