BITKit/Src/Unity/Scripts/Entity/Components/Physics/EntityPhysics.cs

83 lines
2.5 KiB
C#
Raw Normal View History

2023-09-01 14:35:05 +08:00
using System;
2023-06-05 19:57:17 +08:00
using System.Collections;
using System.Collections.Generic;
2023-09-01 14:35:05 +08:00
using System.Threading;
using System.Threading.Tasks;
using BITKit.Entities.Physics;
2023-06-05 19:57:17 +08:00
using UnityEngine;
namespace BITKit.Entities
{
2023-09-01 14:35:05 +08:00
[CustomType(typeof(IEntityPhysics))]
2023-10-24 23:38:22 +08:00
public class EntityPhysics : EntityComponent,IEntityPhysics
2023-06-05 19:57:17 +08:00
{
2023-09-01 14:35:05 +08:00
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody[] rigidbodies;
[SerializeField] private Collider[] ragdollColliders;
2023-10-24 23:38:22 +08:00
[SerializeField] private Joint joint;
2023-09-01 14:35:05 +08:00
[SerializeField] private new Rigidbody rigidbody;
private CancellationToken _cancellationToken;
2023-10-24 23:38:22 +08:00
[Inject]
private IHealth _health;
2023-09-01 14:35:05 +08:00
public override void OnAwake()
2023-06-05 19:57:17 +08:00
{
2023-10-24 23:38:22 +08:00
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
2023-09-01 14:35:05 +08:00
_cancellationToken = entity.Get<CancellationToken>();
2023-06-05 19:57:17 +08:00
}
2023-10-24 23:38:22 +08:00
private async void OnSetAlive(bool alive)
2023-06-05 19:57:17 +08:00
{
2023-09-01 14:35:05 +08:00
IsPhysics = !alive;
if (animator)
animator.enabled = alive;
try
2023-06-05 19:57:17 +08:00
{
2023-09-01 14:35:05 +08:00
await Task.Delay(10, _cancellationToken);
rigidbodies.ForEach(x => { x.isKinematic = alive; });
ragdollColliders.ForEach(x => { x.enabled = !alive; });
OnSetPhysics?.Invoke(!alive);
}
catch (OperationCanceledException)
2023-06-05 19:57:17 +08:00
{
2023-09-01 14:35:05 +08:00
}
2023-10-24 23:38:22 +08:00
if (alive is false && joint is not null)
{
Destroy(joint);
}
2023-09-01 14:35:05 +08:00
2023-06-05 19:57:17 +08:00
}
public void OnSetHP(int hp)
{
}
2023-09-01 14:35:05 +08:00
public Vector3 Center => rigidbody.worldCenterOfMass;
public bool IsPhysics { get; private set; }
public Vector3 Velocity
{
get=>rigidbody.velocity;
set
{
foreach (var x in rigidbodies)
{
x.velocity = value;
}
}
}
public Action<bool> OnSetPhysics { get; set; }
public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force)
{
foreach (var x in rigidbodies)
{
x.AddForce(force, mode);
}
}
public void AddTorque(Vector3 torque, ForceMode mode = ForceMode.Force)
{
foreach (var x in rigidbodies)
{
x.AddTorque(torque, mode);
}
}
2023-06-05 19:57:17 +08:00
}
}