You might think that since your walls are aligned with the coordinate axes, it makes sense to write a special case code (for a vertical wall, negate the x coordinate for speed, for a horizontal wall, negate the y-coordinate of speed). However, as soon as you play well with vertical and horizontal walls, perhaps the next thing you will think about is: "What about walls at arbitrary angles?" Therefore, it is worth considering the general case from the very beginning.
In the general case, suppose your rocket has velocity v and hits a wall with a normal surface n .

Divide v into components u , perpendicular to the wall, and w .

Where:
u = ( v - n / n - n ) n
w = v - u
Here v - n - dot product of vectors v and n . See Link for an explanation of how to calculate it. The point product n - n estimates the square of the length of the normal vector; if you always save your normals as unit vectors , then n n = 1, and you can omit division.
After bouncing, the motion component parallel to the wall depends on friction f, and the component perpendicular to the wall depends on elasticity, which can be set in the form of a restitution coefficient r.
So, the velocity after the collision is v ' = f w - r u . In an ideal elastic, friction-free collision, v ' = w - u ; those. the movement is reflected relative to the normal at the point of collision, as in the diagram given in Bill's answer.
This approach works the same way in three dimensions.
(Obviously, this is a very simplified concept of bouncing, it does not take into account angular momentum or deformation. But for many types of video games, this simplification is quite adequate.)
Gareth Rees Feb 21 '09 at 15:17 2009-02-21 15:17
source share