Ball Physics
Hi guys,
i'm implementing ball physics, which includes ball bouncing off the walls and gravity.
I'm using a separate class for Ball.
Ball Class has
class Ball{
int ballx, bally, vx,vy;
int size = 10;
public Ball()
{
this.ballx = 0;
this.bally = 0;
this.vx = 2;
this.vy = 2;
}
void Move(int canvasWidth, canvasHeight)
{
ballx += vx;
bally += vy;
if ((ballx < 0) || (bally + size > canvasWidth ))
{
vx = -vx;
ballx += vx;
}
if ((bally < 0) || (bally + size > canvasHeight)))
{
vy = -vy;
bally += vy;
}
}
void paint(Graphics g)
{
g.fillArc(this.ballx, this.bally,size, size, 0, 360);
}
}
and the canvas class has
class can extends Canvas implements Runnable
{
int numBall;
Ball ball[]
public can()
{
ball = new Ball[3]; // max 3 balls
balls[0] = new Ball();
numBall = 1;
(new Thread(this)).start();
}
public void paint(Graphics g)
{
for(int i = 0; i < numBall; i++){
ball.Move (getWidth(), getHeight());
ball.paint(g);
}
}
public void run()
{
try{
Thread.sleep(20);
}
catch(Exception e){
}
repaint();
}
public void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case LEFT:
if (numBalls > 1) {
// decrement the counter
numBall = numBall - 1;
ball[numBall] = null;
}
break;
case RIGHT:
// Increase the number of threads
if (numBall < ball.length) {
ball[numBall] = new Ball();
// increment the counter
numBall = numBall + 1;
}
break;
}
}
}
On pressing right key, number of balls needs to be increased. Its creating the new ball but its taking the same ballx , bally as the previous ball
its the problem with the thread right?
i'm starting the thread in constructor. i need to do it using single thread, please guide me.
Thanks

