using System; using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; /// /// 角色状态和信息 /// [DefaultExecutionOrder(-1)] public class CharacterInformation : MonoBehaviour { #region 公有字段 [NonSerialized] public Transform rigRoot; [NonSerialized] public Rigidbody[] rigs; [NonSerialized] public Rigidbody head; [NonSerialized] public bool isGrounded = false; [NonSerialized] public float shortestDistanceFromHeadToGround; [NonSerialized] public Vector3 landPosition; [NonSerialized] public float sinceGrounded; // 从离开地面开始计时 [NonSerialized] public float sinceJumped; [NonSerialized] public float sinceTurn; // #endregion #region 私有字段 private Transform m_HeadTransform; private CheckForGroundCollision[] m_GroundCheckers; #endregion private void Start() { rigRoot = transform.Find("Rigidbodies"); rigs = rigRoot.gameObject.GetComponentsInChildren(); head = rigRoot.Find("Head").GetComponent(); m_GroundCheckers = GetComponentsInChildren(); m_HeadTransform = GetComponentInChildren().transform; shortestDistanceFromHeadToGround = float.MaxValue; } public float GetTotalMass() { float mass = 0; for(int i = 0; i < rigs.Length; ++i) { mass += rigs[i].mass; } return mass; } void FixedUpdate() { sinceTurn += Time.deltaTime; isGrounded = false; shortestDistanceFromHeadToGround = float.MaxValue; for (int i = 0; i < m_GroundCheckers.Length; i++) { if (m_GroundCheckers[i].isGrounded) { float dist = Vector3.Distance(m_HeadTransform.position, m_GroundCheckers[i].collisionPosition); if (dist < shortestDistanceFromHeadToGround) { shortestDistanceFromHeadToGround = dist; landPosition = m_GroundCheckers[i].collisionPosition; } isGrounded = true; } } if(!isGrounded) { sinceGrounded += Time.deltaTime; } else { sinceGrounded = 0; } } public float HeadRayCast() { Ray ray = new Ray(head.transform.position, Vector3.down); RaycastHit mhit; if (Physics.Raycast(ray, out mhit, 20, 1 << 8)) { float height = head.transform.position.y - mhit.point.y; return height; } return shortestDistanceFromHeadToGround; } private void OnDrawGizmos() { //Gizmos.DrawSphere(m_HeadTransform.position, 0.1f); //Gizmos.DrawSphere(landPosition, 0.1f); } }