I have a projection line for my projectiles. The projection line is supposed to show where my projectiles will go even after bouncing off of colliders that have a physics material 2D.
I calculate the reflection from the incoming velocity and multiply it by the material’s bounciness to get my bounce velocity.
The line works as expected as long as my material has a bounciness of 1. If I set the bounciness to anything between 0 and 1, the projection line “undershoots” the projectile. It seems that the physics material is adding a little more to the bounce.
Well, i don’t know how Box2d actually takes the bounce (or “restitution” as it’s called internally) into account, but i’m pretty sure that you must only multiply the reflected part by the bounce value and not the whole velocity. Imagine an almost vertical wall. If the wall as well as the ball has a bounce value of “0”, no bounce should happen at all. If the ball got shoot downwards at the wall, you don’t want to bounce off the wall, but you want to maintain the downward motion. If you multiply the whole velocity by “0” it would make the object to completely stop, no matter at which angle you hit the wall.
So you need to split the velocity into the normal part and the tangent part. The normal part is reflected (inversed) and multiplied by the bounce value. The tangent part should stay the same.
So you should first project the velocity onto the normal to get the “normal part”. Then you can subtract the normal part from the original velocity to get the tangent part. Then just inverse the normal and multiply by bounce and finally combine the two together.
Also keep in mind that Box2d uses the larger bounce value of the two materials involved.
This should work:
Vector3 n = Vector3.Project(vIn, hitNormal);
Vector3 t = vIn - n;
return t - n * GetBounciness();