I’m trying to trap objects (with RigidBody2D
) inside a circle and use the object’s physics material to calculate bouncing/friction with the circle’s border… Yet I can’t figure out how to get less of a bouncy effect but something that transfers the velocity into velocity along the surface (that takes into account this friction/bounciness).
This is basically my current solution:
// offset = vector from center to current position
// distanceSqr = distance from center squared
// radius = radius of the sphere object is trapped in.
if (distanceSqr > radius * radius)
{
// Reflect only if velocity is outwards
float dot = Vector2.Dot(offset.normalized, m_rigidBody.velocity.normalized);
if (dot > 0.0f)
{
// Reflect (Bounce)
m_rigidBody.velocity = Vector3.Reflect(m_rigidBody.velocity, -offset.normalized);
// Drag
m_rigidBody.velocity = m_rigidBody.velocity * (1.0f - (drag));
}
// Trap Position inside
m_transform.position = center + (offset.normalized * radius); // maximum distance (trap inside)
}
Another thing I’ve tried is to remove all outwards velocity of the rigidBody
. But as long as it moves slightly to the side it comes to a halt very quickly because then it removes the upwards vector in sublty different directions and rather soon it removed all of it.
Is there a way to figure out how to calculate a similar resulting velocity vector as it would’ve had if moved up against a point with a normal of an object (which is the information I have) of a regular RigidBody2D
object?
I would love to be able to control the friction and bounciness just like with the Physics2d Material
.
(Pointers on how this works in 3D space to calculate it nicely would - I think - also be good enough to point me in the direction of how to solve this)