49 lines
1.5 KiB
C#
49 lines
1.5 KiB
C#
using UnityEngine;
|
|
using Mirror;
|
|
|
|
public class BasicRigidBodyPush : NetworkBehaviour
|
|
{
|
|
public LayerMask pushLayers;
|
|
public bool canPush;
|
|
[Range(0.5f, 5f)] public float strength = 1.1f;
|
|
|
|
private CharacterController _controller;
|
|
|
|
private void OnControllerColliderHit(ControllerColliderHit hit)
|
|
{
|
|
if (!isLocalPlayer) return;
|
|
|
|
if (isClient && hit != null)
|
|
{
|
|
// if (canPush) CmdPushRigidBodies(hit.gameObject);
|
|
}
|
|
}
|
|
|
|
private void PushRigidBodies(GameObject gameObject)
|
|
{
|
|
// https://docs.unity3d.com/ScriptReference/CharacterController.OnControllerColliderHit.html
|
|
|
|
// make sure we hit a non kinematic rigidbody
|
|
Rigidbody body = gameObject.GetComponent<Collider>().attachedRigidbody;
|
|
if (body == null || body.isKinematic) return;
|
|
|
|
// make sure we only push desired layer(s)
|
|
var bodyLayerMask = 1 << body.gameObject.layer;
|
|
if ((bodyLayerMask & pushLayers.value) == 0) return;
|
|
|
|
// We dont want to push objects below us
|
|
if (_controller.velocity.y < -0.3f) return;
|
|
|
|
// Calculate push direction from move direction, horizontal motion only
|
|
Vector3 pushDir = new Vector3(_controller.velocity.x, 0.0f, _controller.velocity.z);
|
|
|
|
// Apply the push and take strength into account
|
|
body.AddForce(pushDir * strength, ForceMode.Impulse);
|
|
}
|
|
|
|
[Command]
|
|
void CmdPushRigidBodies(GameObject hit)
|
|
{
|
|
PushRigidBodies(hit);
|
|
}
|
|
} |