Collision Detection between two images in Java

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

    is there a problem with:

    Rectangle box1 = new Rectangle(100,100,100,100);
    Rectangle box2 = new Rectangle(200,200,100,100);
    
    // what this means is if any pixel in box2 enters (hits) box1
    if (box1.contains(box2)) 
    {
         // collision occurred
    }
    
    // your code for moving the boxes 
    


    this can also be applied to circles:

    Ellipse2D.Double ball1 = new Ellipse2D.Double(100,100,200,200);
    Ellipse2D.Double ball2 = new Ellipse2D.Double(400,100,200,200);
    
    // what this means is if any pixel on the circumference in ball2 touches (hits)
    // ball1
        if (ball1.contains(ball2)) 
        {
             // collision occurred
        }
    
        // your code for moving the balls
    



    to check whether youve hit the edge of a screen you could use the following:

    Rectangle screenBounds = jpanel.getBounds();
    Ellipse2D.Double ball = new Ellipse2D.Double(100,100,200,200);  // diameter 200
    Rectangle ballBounds = ball.getBounds();
    
    if (!screenBounds.contains(ballBounds))
    {
    // the ball touched the edge of the screen
    }
    

提交回复
热议问题