SamsonGame/Assets/Scripts/Game/Player/Ragdoll.cs

65 lines
1.7 KiB
C#
Raw Normal View History

2021-12-29 20:50:11 +03:00
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);
}
}
}