I know you can use rigid body on two objects for collision and so on. I can do that just fine but I’m trying to do this without needing one on my player object.
But if I have a player object that is using only a character controller, is there any way to “push” them around when colliding with other objects?
CodePudding user response:
As the CharacterController
inherits from Collider
you could do this if the other objects have a (kinematic) Rigidbody
- at least one Rigidbody
is required so the collision itself is detected (not sure on this though, might work without) - and then use Physics.ComputePenetration
in order to calculate the distance and direction you have to move your player in order to move it out of the hit collider => pushing it away.
[RequireComponent(typeof(Rigidbody))]
public class PushCharacter : MonoBehaviour
{
[SerializeField] Collider ownCollider;
void Awake ()
{
if(! ownCollider) ownCollider = GetComponentInChildren<Collider>();
}
void OnCollisionStay(Collision collision)
{
if(collision.collider is CharacterController character)
{
Physics.ComputePenetration(ownCollider, ownCollider.transform.position, ownCollider.transform.rotation, character, character.transform.position, character.transform.rotation, out var direction, out var distance);
character.Move(direction * distance);
}
}
}
Note also
One of the colliders has to be BoxCollider, SphereCollider CapsuleCollider or a convex MeshCollider. The other one can be any type.
Which limits the objects you can use as the pushing objects since the CharacterController
is none of those (even though it kinda acts like a Capsule).
However - just as a heads-up - as soon as there are multiple pushing objects involved this could get quite complex!
CodePudding user response:
Yes, of course it is possible to do it without using built in colliders and rigid bodies. They are just script after all.
One way to do this, is to see if one of the outer bounds of the player object are within Vector3-radius
and Vector3 radius
then apply force to the RigidBody or move the players Vector3.
There are countless possibilities for how to do this but the easiest way is definitely using colliders and RigidBodies..