Files
Hasebe/Assets/Code/OfficeGame/BattleMode/HitBoxes/EntityHitBoxes.cs
T

86 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using Code.OfficeGame.BattleMode.Timeline;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.HitBoxes
{
public class EntityHitBoxes : MonoBehaviour
{
[SerializeField] private Dictionary<HitBoxPartType, BoxCollider> bodyParts;
private readonly Dictionary<Collider, HitBoxPartType> _colliderToPart = new();
private readonly Collider[] _hitResults = new Collider[8];
private LayerMask _hitBoxLayerMask;
private void Awake()
{
_hitBoxLayerMask = LayerMask.GetMask("HitBox");
if (bodyParts != null)
{
foreach (var (part, col) in bodyParts)
{
if (col != null) _colliderToPart[col] = part;
}
}
}
public bool TryGetPartType(Collider col, out HitBoxPartType partType) =>
_colliderToPart.TryGetValue(col, out partType);
public void CheckHitsForCurrentFrame(
IBattleSimulationContext simContext,
Action<Collider, Collider, HitBoxPartType> onTargetHit,
HitBoxPartType attackingBodyPart)
{
if (bodyParts == null || !bodyParts.TryGetValue(attackingBodyPart, out BoxCollider box) || box == null)
return;
simContext?.RecordHitboxVisual(box, Color.red);
Transform boxTransform = box.transform;
Vector3 worldCenter = boxTransform.TransformPoint(box.center);
Vector3 worldHalfExtents = Vector3.Scale(box.size * 0.5f, boxTransform.lossyScale);
int hitsCount = Physics.OverlapBoxNonAlloc(
worldCenter,
worldHalfExtents,
_hitResults,
boxTransform.rotation,
_hitBoxLayerMask,
QueryTriggerInteraction.Collide);
for (int i = 0; i < hitsCount; i++)
{
Collider hitCol = _hitResults[i];
if (hitCol.transform.root == transform.root) continue;
var defenderHitBoxes = hitCol.GetComponentInParent<EntityHitBoxes>();
HitBoxPartType hitPart = HitBoxPartType.Chest;
if (defenderHitBoxes != null)
defenderHitBoxes.TryGetPartType(hitCol, out hitPart);
onTargetHit?.Invoke(box, hitCol, hitPart);
}
}
}
public enum HitBoxPartType
{
Head,
Chest,
LArm,
LElbow,
LWrist,
LLeg,
LKnee,
LAnkle,
RArm,
RElbow,
RWrist,
RLeg,
RKnee,
RAnkle
}
}