I'm making pong, and am finding it really difficult to write an algorithm that bounces the ball off the four walls properly (I will deal with scoring later on, because only part of the West+East sides will be goals). So at the moment I want the ball to bounce around the box.
Detecting whether the ball has hit a wall is easy, but I'm having trouble calculating the new angle.
This is what I've come up with so far:
if(dstY == 0) {
// North wall
if(angle < 90) {
newAngle = angle + 90;
} else {
newAngle = angle - 90;
}
} else if(dstX == maxWidth) {
// East wall
if(angle < 90) {
newAngle = angle + 270;
} else {
newAngle = angle + 90;
}
} else if(dstY == maxHeight) {
// South wall
newAngle = angle + 90;
} else if(dstX == 1) {
// West wall
if(angle < 270) {
newAngle = angle - 90;
} else {
newAngle = angle - 270;
}
}
That only works for about half of the collisions, and looks really ugly. I'm sure this should be really simple and that it's been done many times before.
In my code, dstX/dstY are the X/Y destination coordinates. X=0 and y=0 at the top left.