2017-01-10 3 views
-1

Я делаю игру, в которой игрок должен уклоняться от квадратов, падающих с неба.столкновение и пересечение игроков и площадей

Я пытаюсь сделать так, чтобы, когда игрок пересекается или сталкивается с падающим квадратом, программа заметит.

Я понимаю, что мне нужно получить границы падающих квадратов и игрока, но я не знаю, как это сделать. Буду признателен за любую оказанную помощь.

класс игрока

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(); 
    } 



} 

Прямоугольник класс

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); 
    } 
} 





} 
+0

Не уверен, что я понимаю. Вы знаете текущие 'XLocation',' YLocation' и размер, поэтому вы должны иметь возможность вычислять оценки из них. В чем проблема? – ajb

+0

Я не знаю, как получить оценки для моего массива квадратов – Karavi

+0

Каждый 'Square' имеет метод' GetBounds'. Разве это не работает? Почему вы не можете называть «GetBounds» на каждом квадрате в вашем массиве? – ajb

ответ

1

Вы можете проверить столкновения так же, как вы рисуете квадраты.

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 Метод испытания this прямоугольник againts в rectagle вы передаете к и возвращает истину, если два rectagles пересекаются.

И не забудьте вызвать ваш метод collision один раз на каждой итерации вашего игрового цикла.