Wednesday, September 19, 2018

xna - Vector reflect problem


I'm testing some vector reflection and I want to check what happens when a ball collides with a paddle.


So if I have:


Vector2 velocity = new Vector2(-5, 2); 
position_ball += velocity;

if (position_ball.X < 10)
{

Vector2 v = new Vector2(1,0); // or Vector2.UnitX
velocity = Vector2.Reflect(velocity, v);
}

then, correctly, velocity is (5,2) after Reflect, but if I do:


if (position_ball.X < 10)
{
Vector2 v = new Vector2(1,1);
velocity = Vector2.Reflect(velocity, v);
}


then velocity is (1,8) and not (5, -2) that is the solution of reflection equation R = V - 2 * (V . N)


Why is that?



Answer



The reflection equation is R = V - 2 * (V . N) * N This formula also assumes that N is a normal vector, which it isn't in your case new Vector2(1,1).Length() == 1.414...


Try this instead:


if (position_ball.X < 10)
{
Vector2 v = new Vector2(1,1);
v.Normalize();

velocity = Vector2.Reflect(velocity, v);
}

The reflection of [-5,2] will actually be [-2,5] (or [1,8] if not normalized) and not [5,-2] as you assumed:


R = V - 2 * (V.N) * N
N = [1,1] * 2^-0.5
V = [-5,2]

Since Nx = Ny in this particular case we can refer to either of them as Nc


R = V - 2 * (v.N) * N

= V - 2 * (Vx*Nc + Vy*Nc) * N
= V - 2*Nc(Vx+Vy) * N
= V - 2*Nc(-5+2) * N
= V - 2*Nc(-3) * N
= V + 6*Nc * N
= V + [6*Nx*Nx, 6*Ny*Ny]
= V + [6*Nx^2, 6*Ny^2]
= [6*Nx^2-5, 6*Ny^2+2]
= [6*(2^-1)-5, 6*(2^-1)+2]
= [-2, 5]


(N^a)^b = N^(a*b) which is used in the above proof (2^-0.5)^2 = 2^-1


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...