using UnityEngine; namespace Thousandto.Launcher.ExternalLibs { /// /// 小草的动画 /// public class GrassAnimateScript : VertexAnimateBaseScript { #region//私有变量 //一个随机值 private float _randNum; //风的时间 public float _windTime = Mathf.PI * 2f; //开始摆动计时 public float _time = 0f; //偏移值 public float _offset = 1.4f; //限制最小摆动因子的分母 public int _dePow = 5; //碰撞力度 public Vector2 _power = Vector2.one; //顶点移动方向向量 private Vector3 _dir = Vector3.zero; #endregion #region//重写MonoBehaviour private void OnDisable() { Stop(); } //进入触发器 void OnTriggerEnter(Collider other) { Vector3 dir = transform.position - other.transform.position; //碰撞方向向量 _dir = transform.parent.InverseTransformDirection(dir); dir = _dir; if (other is CapsuleCollider) { var box = other as CapsuleCollider;// UnityUtils.RequireComponent(other.gameObject); //碰撞力度 if (box != null) { if (dir.x > box.radius) dir.x = box.radius; if (dir.z > box.radius) dir.z = box.radius; if (dir.x < box.radius / _dePow) dir.x = box.radius / _dePow; if (dir.z < box.radius / _dePow) dir.z = box.radius / _dePow; float pow_x = Mathf.Abs(dir.x / box.radius); float pow_y = Mathf.Abs(dir.z / box.radius); float cos_x = Mathf.Cos(pow_x); float cos_y = Mathf.Cos(pow_y); _power.x = (1 - pow_x) * _offset * cos_x; _power.y = (1 - pow_y) * _offset * cos_y; } } _dir = _dir.normalized; Play(); } #endregion #region//重写函数 protected override void OnStart() { _windTime = Mathf.PI * 2f; _randNum = UnityEngine.Random.Range(1f, 3f); base.OnStart(); } //刷新顶点之前 protected override bool OnRefreshVertexBefore(ref Vector3 datVertex) { //计算频率 var _frequency = (1.0f - _windTime / (Mathf.PI * 2f)) * 0.7f; //根据时间获取一个角度 //x移动的位置是一个角度的Sin信息 datVertex.x = _dir.x * Mathf.Sin(_time) * _frequency * _power.x; //y方向不做变化 datVertex.y = 0; //z移动的位置是角度+90度后的一个角度的Sin值.x和z的移动方向是垂直的 datVertex.z = _dir.z * Mathf.Sin(_time) * _frequency * _power.y; return true; } //刷新顶点后的处理 protected override void OnRefreshVertexAfter(ref Vector3 datVertex) { if (_windTime < Mathf.PI * 2f) { _windTime += 0.04f; _time += Time.deltaTime + 0.1f; } else { Stop(); } } //播放 protected override void Play() { _time = 0f; _windTime = 0; base.Play(); } //停止 protected override void Stop() { _time = 0f; _windTime = Mathf.PI * 2f; base.Stop(); } #endregion } }