I have created a program that drawing 2 circle on the screen and using keyboard ASWD and arrow key to move around..here is the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BallObject {
private int x;
private int y;
private int radius;
BallObject() {
x=0;
y=0;
radius=0;
}
BallObject (int x,int y,int radius) {
this.x=x;
this.y=y;
this.radius=radius;
}
public void setX(int x) {this.x=x;}
public void setY(int y) {this.y=y;}
public void setRadius(int r) {radius=r;}
public int getX() {return x;}
public int getY() {return y;}
public int getRadius() {return radius;}
}
class Ball extends JFrame implements KeyListener {
BallObject ball1;
BallObject ball2;
Ball() {
super("Simple Ball");
setSize(800,600); //set screen resolution
ball1 = new BallObject(getWidth()/2,getHeight()/2,20);
ball2 = new BallObject(40,40,20);
addKeyListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fill(new Rectangle(0,0,800,600));
//drawing ball1
g2d.setColor(Color.RED);
g2d.fillOval(ball1.getX(),ball1.getY(),ball1.getRadius()*2,ball1.getRadius()*2);
//drawing ball2
g2d.setColor(Color.GREEN);
g2d.fillOval(ball2.getX(),ball2.getY(),ball2.getRadius()*2,ball2.getRadius()*2);
}
public static void main (String args[]) {
new Ball();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_LEFT)
ball1.setX(ball1.getX()-2);
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
ball1.setX(ball1.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_UP)
ball1.setY(ball1.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_DOWN)
ball1.setY(ball1.getY()+2);
if(e.getKeyCode()==KeyEvent.VK_A){
ball2.setX(ball2.getX()-2);
//System.out.println("Hello");
}
if(e.getKeyCode()==KeyEvent.VK_D)
ball2.setX(ball2.getX()+2);
if(e.getKeyCode()==KeyEvent.VK_W)
ball2.setY(ball2.getY()-2);
if(e.getKeyCode()==KeyEvent.VK_S)
ball2.setY(ball2.getY()+2);
repaint();
}
//redraw the screen to show the updated ball location
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
Now i need to test the collision..Once two balls are touching each other.it will show a message "COLLISION DETECTED"..pls help...