I have a very simple Pong game that I've built in Java. The code is quite long so I've decided to focus this question on the collision that occurs with the ball and the bat and also the effects in the game. I'm using ACM Graphics package to learn Java so most of the methods are from that package. I want to know how I can improve this checking process and if the way I revert the speed and direction is efficient. I'm also open to any suggestions for the game.
//Setting up variables
static final int WAIT = 50;
static final int MV_AMT = 20;
static final int BATWIDTH = 120;
static final int BATHEIGHT = 20;
static final int WINDOWX = 400;
static final int WINDOWY = 400;
static final int BALLRADIUS = 10;
private int batX = 150, batY = 400; //Starting positions
private int ballX = 160, ballY = 370;
private int ballSpeedX = 2; //the ball speed on the X axis
private int ballSpeedY = -9; //the ball speed on the Y axis
public void run(){
//... Stuff that runs before the game, ie. draw the sceen etc.
int currentTime = 0;
//Do all our stuff here
while(continueGame){
//Pause dat loop
pause(WAIT);
currentTime = currentTime + WAIT;
//Up the speed every 5 seconds
if (currentTime % 5000 == 0) {
if(ballSpeedY>0)
ballSpeedY += 2;
else
ballSpeedY -= 2;
if(ballSpeedX>0)
ballSpeedX += 2;
else
ballSpeedX -= 2;
}
//Move the ball
ballX=ballX+ballSpeedX;
ballY=ballY+ballSpeedY;
ball.setLocation(ballX, ballY);
//Check
checkCollisions();
}
//... Stuff that gets done after game over
}
public void checkCollisions(){
//This method is quite long so I won't be posting it all
//Just the part the calls the collision method
//Get the bounds
GRectangle batBounds = bat.getBounds();
GRectangle ballBounds = ball.getBounds();
//Where is the ball?
ballX = (int)ball.getX();
ballY = (int)ball.getY();
//Where is the bat?
batX = (int)bat.getX();
batY = (int)bat.getY();
//Did the bat touch the ball?
if(batBounds.intersects(ballBounds)){
batCollision();
}
}
public void batCollision(){
if( ballX+BALLRADIUS > batX+(BATWIDTH/2) ){ //Which side of the bat?
//Which direction is the ball traveling when it hits?
if(ballSpeedX >> 31 !=0){
ballSpeedX = ballSpeedX * -1;
} else {
ballSpeedX = ballSpeedX;
}
} else {
if(ballSpeedX >> 31 !=0){
ballSpeedX = ballSpeedX;
} else {
ballSpeedX = -ballSpeedX;
}
}
ballSpeedY = -ballSpeedY; //Adjust Y speed
}
private
? Also, why aren'tWAIT
andMV_AMT
static
? \$\endgroup\$