65 lines
1.7 KiB
C#
65 lines
1.7 KiB
C#
|
using UnityEngine;
|
||
|
using Random = UnityEngine.Random;
|
||
|
|
||
|
public class Ragdoll : MonoBehaviour
|
||
|
{
|
||
|
private Bone[] _bones;
|
||
|
|
||
|
private void Awake()
|
||
|
{
|
||
|
Rigidbody[] rigidbodies = GetComponentsInChildren<Rigidbody>();
|
||
|
Collider[] colliders = new Collider[rigidbodies.Length];
|
||
|
for (var i = 0; i < rigidbodies.Length; i++)
|
||
|
colliders[i] = rigidbodies[i].GetComponent<Collider>();
|
||
|
|
||
|
_bones = new Bone[rigidbodies.Length];
|
||
|
for (int i = 0; i < _bones.Length; i++)
|
||
|
_bones[i] = new Bone(rigidbodies[i], colliders[i]);
|
||
|
|
||
|
_bones.ForEach(b => b.SetActive(false));
|
||
|
}
|
||
|
|
||
|
|
||
|
public void EnableRagdoll(Vector3 direction, float strength)
|
||
|
{
|
||
|
if(_bones.Length == 0)
|
||
|
return;
|
||
|
|
||
|
_bones[0].SetActive(true);
|
||
|
_bones[0].AddTorque(direction.normalized * 3600);
|
||
|
foreach (Bone bone in _bones)
|
||
|
{
|
||
|
bone.SetActive(true);
|
||
|
bone.AddForce(direction * strength);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private struct Bone
|
||
|
{
|
||
|
private readonly Rigidbody _rigidbody;
|
||
|
private readonly Collider _collider;
|
||
|
|
||
|
public Bone(Rigidbody rigidbody, Collider collider)
|
||
|
{
|
||
|
_rigidbody = rigidbody;
|
||
|
_collider = collider;
|
||
|
}
|
||
|
|
||
|
public void SetActive(bool isActive)
|
||
|
{
|
||
|
_rigidbody.isKinematic = !isActive;
|
||
|
_collider.enabled = isActive;
|
||
|
}
|
||
|
|
||
|
public void AddForce(Vector3 force)
|
||
|
{
|
||
|
_rigidbody.AddForce(force, ForceMode.VelocityChange);
|
||
|
}
|
||
|
|
||
|
public void AddTorque(Vector3 force)
|
||
|
{
|
||
|
_rigidbody.AddTorque(force, ForceMode.VelocityChange);
|
||
|
}
|
||
|
}
|
||
|
}
|