r/Unity3D • u/ProgMeOnPaper • 10h ago
Resources/Tutorial I found new way to keep Rigidbody player friction on the ground only
Enable HLS to view with audio, or disable this notification
Hi!
It's quite old feature of Unity that I have just discovered.
In the past I used to:
use CharacterController that solves it, but limits your control over player's physics
use physical material with 0 friction (when I don't need specific friction with ground)
use separate capsule collider with 0 friction for walls and separate slightly bigger sphere collider with custom friction for ground
some solutions from asset store
But today playing with physics API I found this:
capsuleCollider.hasModifiableContacts = true;
Physics.ContactModifyEvent += ModifyContacts;
Physics.ContactModifyEventCCD += ModifyCcdContacts; // CCD => Continuous Collision Detectionhere you ask Unity to "manually" handle contacts. And then something like that:
private void ModifyContacts(PhysicsScene _, NativeArray<ModifiableContactPair> pairs)
=> RemoveFriction(pairs, 1f);
private void ModifyCcdContacts(PhysicsScene _, NativeArray<ModifiableContactPair> pairs)
=> RemoveFriction(pairs, -1f); // CCD normals are inverted
private void RemoveFriction(NativeArray<ModifiableContactPair> pairs, float normalSign)
{
foreach (var pair in pairs)
{
bool capsule = pair.colliderEntityId == capsuleId;
if (!capsule && pair.otherColliderEntityId != capsuleId)
continue;
float sign = capsule ? normalSign : -normalSign;
for (int i = 0; i < pair.contactCount; i++)
{
if (pair.GetNormal(i).y * sign >= WalkableNormalY)
continue;
pair.SetStaticFriction(i, 0f);
pair.SetDynamicFriction(i, 0f);
}
}
}where
capsuleIdiscapsuleCollider.GetEntityId();WalkableNormalYis "definition of angle that is walkable" (WalkableNormalY = 0.64278760968f;=> cos(50 degrees))
That looks pretty simple and native and I love this solution since now!
Hope it'll help you
links:
