Search code examples
javascriptmathgame-physics

How to calculate reflection angle of a ball colliding with a wall


I have a ball and I'm moving it toward an angle like this:

ball.x += ball.speed * Math.sin(ball.angle)
ball.y += ball.speed * -Math.cos(ball.angle)

How can I calculate the reflection angle when the ball collides with a wall?(horizontal or vertical)

Something like this


Solution

  • For any wall with normal vector e_n a ball with initial velocity vector v_i has the velocity vector v_f after reflection with

    v_f = v_i - 2 dot( v_i, e_n) e_n,

    where dot is the vector dot-product.

    Explanation: The projection of v_i on e_n is dot( v_i, e_n ). This is the velocity towards the wall and this is the part that gets reversed upon reflection. The component p = dot( v_i, e_n ) results in a vector p e_n. The remaining component can be calculated via a cross product or simply v_s = v_i - p e_n. The final velocity is the non altered component plus the reversed projected component, i.e. v_s - p e_n = v_i - 2 p e_n = v_i - 2 dot( v_i, e_n) e_n