using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
public enum colliderobj
{
无,
汽车,
被撞行人
}
///
/// 碰撞脚本
///
public class Overturn_Car : MonoBehaviour
{
public Vector3 targetPosition = new Vector3(815.2605f, 12f, 393.95f);
public Vector3 targetRotation = new Vector3(0f, 0f, 120f);
public float animationDuration = 1.0f; // 动画持续时间,
public Transform box_Car;
public colliderobj colliderObj = colliderobj.无; //被撞到的人
[Header("叉车撞人")]
public Animator personAni; //被撞行人动画
public Transform box_person;
private void Start()
{
CheckComponents();
}
// 用于3D物理碰撞检测(非触发器)
void OnCollisionEnter(Collision collision)
{
Debug.Log("碰撞发生了!碰撞对象: " + collision.gameObject.name);
Debug.Log("Tag: " + collision.gameObject.tag);
Debug.Log("Layer: " + collision.gameObject.layer);
if (collision.gameObject.name == "撞车箱子")
{
DetachFromParent();
StartFlipAnimation();
}
if (collision.gameObject.name == "撞人箱子")
{
personAni.SetTrigger("被撞");
Rigidbody box_personRig = box_person.gameObject.GetComponent();
Destroy(box_personRig);
}
}
#region 撞车
///
/// 把箱子从叉车的子物体上移除
///
void DetachFromParent()
{
if (box_Car.transform.parent != null)
{
Debug.Log($"从父物体 {box_Car.transform.parent.name} 中脱离");
transform.SetParent(null, true); // 第二个参数为true表示保持世界坐标不变
StartCoroutine(stopBox());
}
else
{
Debug.Log("该物体没有父物体");
}
}
///
/// 停止箱子滚动(去除刚体)
///
///
IEnumerator stopBox()
{
yield return new WaitForSeconds(1.5f);
Rigidbody rb = box_Car.GetComponent();
if (rb!= null)
{
Destroy(rb);
}
}
void StartFlipAnimation()
{
// 停止可能正在进行的旧动画
transform.DOKill();
// 创建动画序列
Sequence flipSequence = DOTween.Sequence();
flipSequence.Join(transform.DOMove(targetPosition, animationDuration).SetEase(Ease.OutCubic));
flipSequence.Join(transform.DORotate(targetRotation, animationDuration, RotateMode.FastBeyond360).SetEase(Ease.OutCubic));
// 动画完成后可以执行其他操作
flipSequence.OnComplete(() => {
Debug.Log("翻转动画完成!物体已独立");
});
}
#endregion
#region 撞人
// 将Tag映射到枚举的辅助方法
private colliderobj GetColliderObjFromTag(string tag)
{
switch (tag)
{
case "汽车": return colliderobj.汽车;
case "被撞行人": return colliderobj.被撞行人;
default: return colliderobj.无;
}
}
///
/// 寻找物体上的collider和rigidbody
///
void CheckComponents()
{
Collider col = GetComponent();
Rigidbody rb = GetComponent();
Debug.Log("=== 碰撞组件检查 ===");
Debug.Log("Collider: " + (col != null ? col.GetType().Name : "无"));
if (col != null) Debug.Log("IsTrigger: " + col.isTrigger);
Debug.Log("Rigidbody: " + (rb != null ? "存在" : "无"));
if (rb != null) Debug.Log("IsKinematic: " + rb.isKinematic);
Debug.Log("===================");
}
#endregion
}