-1

I am currently making a Space Shooter in Java. I am able to make bullets shoot and enemies come from the top, but I am not sure how to check if they intersect. I understand that the Rectangle class has a intersects method, but I am not sure how I would place the rectangles around the bullets and the enemies, since I don't know beforehand how many may be on the screen. How can I do this? Here is my code:

Game.java

package main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Game extends Canvas implements Runnable, KeyListener {

    //declare values
    private static final long serialVersionUID = 1L;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    public static final String TITLE = "Space Shooter";

    private boolean running = false;
    private Thread thread;

    private Player player;

    private BufferedImage playerImage;
    private BufferedImage bulletImage;
    private BufferedImage enemyImage;

    int playerx;
    int playery;

    int round = 1;

    public Game() {
        //
        player = new Player((WIDTH/2)-32, HEIGHT-200); 

        //allocates all file resources
        try {
            playerImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/player.png"));
            bulletImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/bullet.png"));
            enemyImage = ImageIO.read(this.getClass().getResourceAsStream("/resources/enemy.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        addKeyListener(this);
        setFocusable(true);
        requestFocusInWindow();
    }

    //starts thread
    private synchronized void start() {
        if (running)
            return;

        running = true;
        thread = new Thread(this);
        thread.start();
    }

    //stops thread
    private synchronized void stop() {
        if (!running)
            return;

        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(1);
    }

    @Override
    //game loop
    public void run() {     
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60.0;
        double ns  = 1000000000 / amountOfTicks;
        double delta = 0;
        int updates = 0;
        int frames = 0;
        long timer = System.currentTimeMillis();
        while (running) {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            if (delta > 1) {
                tick();
                updates++;
                delta--;
            }
            Shoot.updateBullets();
            Enemy.updateEnemies();
            render();
            frames++;

            if (System.currentTimeMillis() - timer > 1000) {
                timer += 1000;
                System.out.println(updates + " TICKS, " + frames + " FPS");
                updates = 0;
                frames = 0;
            }
        }
        stop(); 
    }

    //updates sprite locations
    public void tick() {
        playerx = player.getX();
        playery = player.getY(); 
    }

    //renders sprites
    public void render() {
        //setting up triple-buffering
        BufferStrategy bs = this.getBufferStrategy();
        if (bs == null) {
            createBufferStrategy(3);
            return;
        }
        Graphics g  = bs.getDrawGraphics();

        //////////////////////////////////

        g.setColor(Color.BLACK); g.fillRect(0,0,getWidth(), getHeight());
        g.drawImage(playerImage, playerx, playery, this); 

        if (Shoot.allBullets.size() != 0) {
            for (int i = 0; i < Shoot.allBullets.size(); i++) {
                int bulletx = (int) Shoot.allBullets.get(i).x;
                int bullety = (int) Shoot.allBullets.get(i).y;  
                g.drawImage(bulletImage, bulletx + 21, bullety, this);
            }
        }

        if (Enemy.allEnemies.size() != 0) {
            for (int i = 0; i < Enemy.allEnemies.size(); i++) {
                int enemyx = (int) Enemy.allEnemies.get(i).x;
                int enemyy = (int) Enemy.allEnemies.get(i).y;
                g.drawImage(enemyImage, enemyx, enemyy, this);
            }
        } else {
            Enemy.createEnemies(round);
            round++;
        }

        //////////////////////////////////

        g.dispose();
        bs.show();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_SPACE) {
            Shoot.addBullet(player.getX(), player.getY());
        }
    }

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_UP) {
            player.setY(playery -= 20);
        } else if (key == KeyEvent.VK_DOWN) {
            player.setY(playery += 20);
        } else if (key == KeyEvent.VK_RIGHT) {
            player.setX(playerx += 40);
        } else if (key == KeyEvent.VK_LEFT) {
            player.setX(playerx -= 40);
        } 
    }

    public void keyTyped(KeyEvent e) {}

    public static void main(String[] args) {

        Game game = new Game();
        JFrame frame = new JFrame(TITLE);

        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(game);
        frame.getContentPane().setBackground(Color.BLACK);
        frame.setVisible(true); 

        game.start();

    }

}

Shoot.java

package main;

import java.util.ArrayList;

public class Shoot {

    static ArrayList<Point> allBullets = new ArrayList<Point>();

    public static void addBullet(int x, int y) {
        allBullets.add(new Point(x, y)); 
    }

    public static ArrayList<Point> getAllBulletPosistions() {
        return allBullets;
    }

    public static void updateBullets() {
        if (allBullets.size() != 0) {
            for (int i = 0; i < allBullets.size(); i++) {
                allBullets.get(i).y -= 1; 
            }
        }
    }

}

Enemy.java

package main;

import java.util.ArrayList;

public class Enemy {

    static ArrayList<Point> allEnemies = new ArrayList<Point>();

    public static ArrayList<Point> createEnemies(int round) {
        for (int i = 0; i < round; i++) {
            Point newEnemyLocation = new Point((int) (Math.random()*Game.WIDTH - 64), 0);
            if (newEnemyLocation.x < 64) {
                newEnemyLocation.x += 70;
            } 
            allEnemies.add(newEnemyLocation);
        }
        return allEnemies; 
    }

    int validate(int xpos) {
        if (xpos > Game.WIDTH - 64) {
             xpos -= 64;
        }
        if (xpos < 64) {
            xpos += 64;
        }
        return xpos;
    }

    public static ArrayList<Point> updateEnemies() {
        if (allEnemies.size() != 0) {
            for (int i = 0; i < allEnemies.size(); i++) {
                Point enemyLocation = allEnemies.get(i);
                if (enemyLocation.y <= Game.HEIGHT) {
                    allEnemies.get(i).y += 0.1;
                } else {
                    allEnemies.remove(i);
                }   
            }
        }
        return allEnemies;
    }

}
the fool
  • 19
  • 5

1 Answers1

1
for(int i = 0; i < Shoot.allBullets.size(); i++){  

for(int j = 0; j < Enemy.allEnemys.size(); j++){

if(new Rectangle(Shoot.allBullets.get(i).x,Shoot.allBullets.get(i).y, width, height).intersects(new Rectangle(Enemy.allEnemys.get(j).x, Enemy.allEnemys.get(j).y, width, height)){
//on intersect
}

}
}

This would work but you shouldn't create new rectangles like this instead you should create a bullet class and a Enemy class that both contains the position and Rectangle anyways good luck!

WilliamTaco
  • 123
  • 9
  • Thanks a lot! I will try the bullet/enemy class method and if that doesn't work out, I will use the method u put here. – the fool Mar 02 '16 at 04:04
  • I did this and it is able to detect the collisions, but now, when I fire a second bullet, the game crashes and gives the following exception: Exception in thread "Thread-1" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.rangeCheck(ArrayList.java:638) at java.util.ArrayList.get(ArrayList.java:414) at main.Game.checkCollisions(Game.java:185) at main.Game.tick(Game.java:118) at main.Game.run(Game.java:95) at java.lang.Thread.run(Thread.java:745) – the fool Mar 02 '16 at 05:30
  • @thefool I'm sorry, just saw why you are getting the error, I messed up and used "i" in the allEnemys.get but it should be 'j" I edited my answer so take a look at it now – WilliamTaco Mar 02 '16 at 11:41