Collision Detection between two images in Java

前端 未结 9 1930
情歌与酒
情歌与酒 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:45

    First, use the bounding boxes as described by Jonathan Holland to find if you may have a collision.

    From the (multi-color) sprites, create black and white versions. You probably already have these if your sprites are transparent (i.e. there are places which are inside the bounding box but you can still see the background). These are "masks".

    Use Image.getRGB() on the mask to get at the pixels. For each pixel which isn't transparent, set a bit in an integer array (playerArray and enemyArray below). The size of the array is height if width <= 32 pixels, (width+31)/32*height otherwise. The code below is for width <= 32.

    If you have a collision of the bounding boxes, do this:

    // Find the first line where the two sprites might overlap
    int linePlayer, lineEnemy;
    if (player.y <= enemy.y) {
        linePlayer = enemy.y - player.y;
        lineEnemy = 0;
    } else {
        linePlayer = 0;
        lineEnemy = player.y - enemy.y;
    }
    int line = Math.max(linePlayer, lineEnemy);
    
    // Get the shift between the two
    x = player.x - enemy.x;
    int maxLines = Math.max(player.height, enemy.height);
    for ( line < maxLines; line ++) {
        // if width > 32, then you need a second loop here
        long playerMask = playerArray[linePlayer];
        long enemyMask = enemyArray[lineEnemy];
        // Reproduce the shift between the two sprites
        if (x < 0) playerMask << (-x);
        else enemyMask << x;
        // If the two masks have common bits, binary AND will return != 0
        if ((playerMask & enemyMask) != 0) {
            // Contact!
        }
    
    }
    

    Links: JGame, Framework for Small Java Games

提交回复
热议问题