Search code examples
javacollision-detectioncollisionbounds

collision and intersection of player and squares


I am making a game where a player must dodge squares that are falling from the sky.

I am trying to make it so that when the player intersects or collides with a falling square, the program will notice.

I realize that i have to get the bounds of the falling squares and the player, but i do not know how to do so. Any help is much appreciated.

Player class

import javax.swing.*;
import java.awt.*;
import java.awt.Rectangle;


public class Player extends JPanel { 
     private int XLocation;
     private int squareSize;
     private int YLocation ;
     private int MoveSpeed;
     int xMouse, yMouse;


public int XLocation(){
    return XLocation = 300;
}

public int YLocation(){
    return YLocation = 750;
}

public int SquareSize(){ 
    return squareSize = 20;
}  

public void paint(Graphics g){
    g.setColor(Color.GRAY);
    g.fillRect(XLocation,YLocation,squareSize,squareSize);
}

public Rectangle bounds(){ 
 return(new Rectangle(XLocation,YLocation,20,20));
}

public int MoveSpeed(){
    return MoveSpeed = 23;
}

 public Player(){
    XLocation();
    SquareSize();
    MoveSpeed();
    YLocation();
}


   public void PlayerMove(java.awt.event.MouseEvent evt){
        XLocation = evt.getX();
        YLocation = evt.getY();
   }



}

The rectangle class

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.Random;

public class Square {

private int XLocation;
private int Size;
private int YLocation = -Size;
private int fallSpeed = 1;
Random rand = new Random();



public int generateRandomXLocation(){
    return XLocation = rand.nextInt(Game.WINDOW_WIDTH - Size);
}


public int generateRandomSquareSize(){ 
    return Size = rand.nextInt((30-17)+1)+17;
}



public int generateRandomFallSpeed(){
    return fallSpeed = rand.ints(3, 3, 8).findFirst().getAsInt();
}


public void paint(Graphics g){
    g.setColor(Color.BLACK);
    g.fillRect(XLocation,YLocation,Size,Size);
}


public Square(){
    generateRandomXLocation();
    generateRandomSquareSize();
    generateRandomFallSpeed();
}



public void update(){


    if(YLocation >= Game.WINDOW_HEIGHT){
        generateRandomXLocation();
        generateRandomFallSpeed();
        generateRandomSquareSize();
        YLocation = -Size;
    }

    //moves the square down if the square is inside the window
    if(YLocation <= Game.WINDOW_HEIGHT){
        YLocation += fallSpeed;
    }
}
public void GetBounds(){
    Rectangle rectangle = new Rectangle(XLocation,YLocation,Size,Size); 
} 
}

Game Class

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class Game extends JPanel { 

public static final int WINDOW_WIDTH = 600;
public static final int WINDOW_HEIGHT = 900;


Square[] squareArray = new Square[20];

Player thePlayer = new Player();


public Game() {

    //initializes square objects
    for (int i = 0; i < squareArray.length; i++)
        squareArray[i] = new Square();


}

public void paint(Graphics graphics) {


    graphics.setColor(Color.WHITE); 
    graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    //paints square objects to the screen
    for (Square aSquareArray : squareArray) {
        aSquareArray.paint(graphics);    
    }
    thePlayer.paint(graphics); 

}

public void update() {
    for (Square aSquareArray : squareArray) aSquareArray.update();
}



  private void mouseMove(MouseEvent evt) {
      thePlayer.PlayerMove(evt);  
} 


 public void collision(){
  Rectangle rectangle1 = thePlayer.bounds(); 
  }


public static void main(String[] args) throws InterruptedException {

    Game game = new Game();
    Player thePlayer = new Player();

    JFrame frame = new JFrame();
    frame.add(game);
    frame.setVisible(true);
    frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setTitle("Raining Multiple Squares");
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);

    BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);


   Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
cursorImg, new Point(0, 0), "blank cursor");


  frame.getContentPane().setCursor(blankCursor);


          frame.addMouseMotionListener(new    java.awt.event.MouseMotionAdapter() {
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            mouseMove(evt); 
        } 

        private void mouseMove(MouseEvent evt){
            game.mouseMove(evt); 
        }
    });

    while (true) {
        game.update();
        game.repaint(); 
        Thread.sleep(10);
    }
}





}

Solution

  • You can test collision the same way you are painting the squares.

     public void collision(){
         Rectangle rectangle1 = thePlayer.bounds();//player rectangle 
         for (Square square: squareArray) {
            if(square.GetBounds().intersects(rectangle1)){//testing all squares vs player
                //if you are here a collision happened
                //you can remome square add score ...
            }  
        } 
     }
    

    intersects method test this rectangle againts the rectagle you are passing to and returns true if the two rectagles are intersecting.

    And don't forget to call your collisionmethod once every iteration of your game loop.