Hello everyone
I am creating a small game and have come to the point where I need to use collision detection. The problem is, I do not exactly know how to create basic collision with rectangles. I now it requires you to import java.awt.Rectangle but thats about it as far as what has worked for me.
This is my cobblestone class. The image is 20x20 pixels, I need collision for this.package outrun; import java.awt.Image; import javax.swing.ImageIcon; public class Cobblestone { private String cobblestone = "/resources/cobblestone_outrun.png"; private Image image; public Cobblestone() { ImageIcon i = new ImageIcon(this.getClass().getResource(cobblestone)); image = i.getImage(); } public Image getImage() { return image; } }
This is my person class, I also need collision for this.package outrun; import java.awt.Image; import java.awt.event.KeyEvent; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Person { private String person = "/resources/person_outrun.png"; private int dx; private int dy; private int x; private int y; private Image image; public Person() { ImageIcon i = new ImageIcon(this.getClass().getResource(person)); image = i.getImage(); x = 31; y = 175; } public void move() { x += dx; y += dy; } public int getX() { return x; } public int getY() { return y; } public Image getImage() { return image; } public void KeyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_RIGHT) { dx = 1; } if (key == KeyEvent.VK_LEFT) { dx = -1; } if (key == KeyEvent.VK_UP) { dy = -1; } if (key == KeyEvent.VK_DOWN) { dy = 1; } } public void KeyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_RIGHT) { dx = 0; } if (key == KeyEvent.VK_LEFT) { dx = 0; } if (key == KeyEvent.VK_UP) { dy = 0; } if (key == KeyEvent.VK_DOWN) { dy = 0; } } }
Do I determine the collision method in my board.class? What I wish to happen is if the person intersects the cobblestone, the person stops (dx = 0 and dy = 0). How would I go about doing this? Thanks! Any help would be greatly appreciated!