Collision Detection between two images in Java

前端 未结 9 1948
情歌与酒
情歌与酒 2020-11-27 06:53

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,         


        
9条回答
  •  野性不改
    2020-11-27 07:38

    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.

提交回复
热议问题