BasicRigidBodyPush.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using UnityEngine;
  2. public class BasicRigidBodyPush : MonoBehaviour
  3. {
  4. public LayerMask pushLayers;
  5. public bool canPush;
  6. [Range(0.5f, 5f)] public float strength = 1.1f;
  7. private void OnControllerColliderHit(ControllerColliderHit hit)
  8. {
  9. if (canPush) PushRigidBodies(hit);
  10. }
  11. private void PushRigidBodies(ControllerColliderHit hit)
  12. {
  13. // https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html
  14. // make sure we hit a non kinematic rigidbody
  15. Rigidbody body = hit.collider.attachedRigidbody;
  16. if (body == null || body.isKinematic) return;
  17. // make sure we only push desired layer(s)
  18. var bodyLayerMask = 1 << body.gameObject.layer;
  19. if ((bodyLayerMask & pushLayers.value) == 0) return;
  20. // We dont want to push objects below us
  21. if (hit.moveDirection.y < -0.3f) return;
  22. // Calculate push direction from move direction, horizontal motion only
  23. Vector3 pushDir = new Vector3(hit.moveDirection.x, 0.0f, hit.moveDirection.z);
  24. // Apply the push and take strength into account
  25. body.AddForce(pushDir * strength, ForceMode.Impulse);
  26. }
  27. }