Thursday, 3 January 2008

A Bat and Ball

I decided to code up the game as a Java applet, to give myself a bit of practice with Java.

I have a bat, controlled by the up and down arrow keys, and a ball that generally bounces off the bat. One significant bug that still hasn't been ironed out is that occasionally the ball tends to stick inside the bat when the bat moves into the ball, and vibrates like a crazy thing along one of the edges until escapes. I need to give some thought as to how to fix this, which probably involves increasing the ball's velocity as the bat moves up into it. Anyway, a screenshot is below; I think this might be a Call of Duty 4 killer.



The obvious things to move on to are to fix the dodgy collision detection, and make it possible to lose. Less obvious is that this is all in one mega-class at the moment, and needs to be split into a main method, a ball class, and a bat class. The graphics also double-buffered, supposedly, but I'm not completely convinced that's working.

The code for the collision detection, for those who might be interested, is below:

// bounce ball if it touches the paddle
// ball centre is (xpos,ypos)

if (x_pos <= paddle_x+paddle_width+radius) {

if (y_pos >= paddle_y && y_pos <= paddle_y+paddle_height) {
x_velocity *= -1;
}

if (y_pos + radius >= paddle_y && y_pos + radius <= paddle_y+paddle_vel ) {
y_velocity = -1; // need to generalise this
}
if (y_pos - radius <= paddle_y+paddle_height &&
y_pos - radius >= paddle_y+paddle_height - paddle_vel) {
y_velocity = 1;
}
}

x_pos += x_velocity;

y_pos += y_velocity;