MayHeCome/Assets/XX/WoodElasticHit.cs
2024-12-18 17:55:34 +08:00

111 lines
3.3 KiB
C#

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//适用于木雕和树木,点击时的摇晃效果
public class WoodElasticHit : MonoBehaviour
{
public float hitDuration = 1f; // 受击反馈持续时间
public float scaleAmount = 0.05f; // 缩放量
public float rotationAngle = 5f; // 旋转角度
public float damping = 10f; // 阻尼系数
public bool isTree;
public GameObject TargetGameObject;// 每次受击间隔时间
private Vector3 originalScale;
private Quaternion originalRotation;
private List<Transform> ScupBranches = new List<Transform>();
void Start()
{
originalScale = TargetGameObject.transform.localScale;
originalRotation = TargetGameObject.transform.rotation;
if (!isTree)
{
for (int i = 0; i < TargetGameObject.transform.childCount; i++)
{
ScupBranches.Add(TargetGameObject.transform.GetChild(i));
}
}
}
private Coroutine elasticFeedbackCoroutine;
private int currentStageInt = 0;
public void OnHit(float stage)
{
Debug.Log("Hit! "+stage);
//摇晃效果
if (elasticFeedbackCoroutine != null)
{
StopCoroutine(elasticFeedbackCoroutine);
}
elasticFeedbackCoroutine = StartCoroutine(ElasticFeedback());
//木像掉落效果
if (!isTree)
{
//Debug.Log(currentStageInt + " + " + stage);
if (Mathf.FloorToInt(stage*(ScupBranches.Count-1)) > currentStageInt )
{
Debug.Log(currentStageInt + " - " + stage);
currentStageInt++;
Animator branchAnimator = ScupBranches[currentStageInt - 1].GetComponent<Animator>();
if (branchAnimator != null)
{
// 触发掉落动画
branchAnimator.SetTrigger("FallTrigger");
}
}
// 检查 Animator 是否存在
}
}
public void ResetBranch()
{
Debug.Log("木像台重置源头");
currentStageInt = 0;
for (int i = 0; i < ScupBranches.Count; i++)
{
Animator branchAnimator = ScupBranches[i].GetComponent<Animator>();
if (branchAnimator!= null)
{
branchAnimator.SetTrigger("UpTrigger");
}
}
}
IEnumerator ElasticFeedback()
{
float timeElapsed = 0f;
while (timeElapsed < hitDuration)
{
timeElapsed += Time.deltaTime;
float progress = timeElapsed / hitDuration;
float dampenedSin = Mathf.Sin(progress * Mathf.PI * damping) / (progress * damping + 1);
float scaleFactor = 1 - (scaleAmount * dampenedSin);
TargetGameObject.transform.localScale = new Vector3(originalScale.x * scaleFactor, originalScale.y * scaleFactor, originalScale.z);
float rotationFactor = rotationAngle * dampenedSin;
TargetGameObject.transform.rotation = Quaternion.Euler(0, 0, originalRotation.eulerAngles.z + rotationFactor);
yield return null;
}
TargetGameObject.transform.localScale = originalScale;
TargetGameObject.transform.rotation = originalRotation;
}
}