I am coding a game that is a maze and im trying to figure out where to put my collision detection but anywhere it try it it doesnt work... i tried to put it int o multiple classes but it got to confuzing so i started basic. the code is... please help!
package ballgame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
//create class that extends JFrame
public class BALLGAME extends JFrame implements Runnable {
double p1speed = .5, p2speed = .5;
int x, y, xDirection, yDirection;
private Image dbImage;
private Graphics dbGraphics;
Image face;
public void run(){
try{
while(true){
move();
Thread.sleep(3);
}
}catch(Exception e){
System.out.println("ERROR");
}
}
public void move(){
x += xDirection;
y += yDirection;
if(x <= 0)
x=0;
if(x>= 1180)
x=1180;
if(y <= 20)
y = 20;
if(y >= 780)
y = 780;
}
public void setXDirection(int xdir){
xDirection = xdir;
}
public void setYDirection(int ydir){
yDirection = ydir;
}
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int Keycode = e.getKeyCode();
if(Keycode == e.VK_UP){
setYDirection(-1);
}
if(Keycode == e.VK_LEFT){
setXDirection(-1);
}
if(Keycode == e.VK_DOWN){
setYDirection(+1);
}
if(Keycode == e.VK_RIGHT){
setXDirection(+1);
}
}
public void keyReleased(KeyEvent e){
int Keycode = e.getKeyCode();
if(Keycode == e.VK_UP){
setYDirection(0);
}
if(Keycode == e.VK_LEFT){
setXDirection(0);
}
if(Keycode == e.VK_DOWN){
setYDirection(0);
}
if(Keycode == e.VK_RIGHT){
setXDirection(0);
}
}
}
//constructor to create frame properties
public BALLGAME(){
setTitle("spanky babies");
addKeyListener(new AL());
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
//main method
public static void main(String [] args){
//calls the frame
BALLGAME t = new BALLGAME();
Thread t1 = new Thread(t);
t1.start();
}
public void paint(Graphics g){
dbImage =createImage(getWidth(), getHeight());
dbGraphics = dbImage.getGraphics();
paintCopmponent(dbGraphics);
g.drawImage(dbImage, 0, 0, this);
}
// a graphics method allowing you to access the graphics to draw on the screen
public void paintCopmponent(Graphics g){
Rectangle p1 = new Rectangle(250,750,20,20);
Rectangle ob = new Rectangle(200,250,90,90);
g.setColor(Color.GRAY);
g.fillRect(ob.x, ob.y, ob.width, ob.height);
g.setColor(Color.blue);
//draw player 1
g.fillRect(x, y,p1.width, p1.height);
if(p1.intersects(ob)){
//to test if it works
System.out.println("x");
}
//Collision
//paint it all
repaint();
}
}