using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { Rigidbody2D rb; [HideInInspector]public Animator anim; [HideInInspector]public PhysicsCheck physicsCheck; [Header("基本参数")] public float normalSpeed;//正常速度 public float chaseSpeed;//追击速度 [HideInInspector] public float currentSpeed;//当前速度 public Vector3 faceDir;//面朝方向 public float hurtForce;//受伤的力 public Transform attacker;//攻击者 [Header("计时器")] public float waitTime; public float waitTimeCounter; public bool wait; [Header("状态")] public bool isHurt; public bool isDead; private BaseState currentState; protected BaseState patrolState; protected BaseState chaseState; protected virtual void Awake() { rb = GetComponent(); anim = GetComponent(); physicsCheck = GetComponent(); currentSpeed = normalSpeed; waitTimeCounter = waitTime; } public void OnEnable() { // currentState = patrolState; // currentState.OnEnter(this); } public void Update() { faceDir = new Vector3(-transform.localScale.x,0,0); if (physicsCheck.touchLeftWall && faceDir.x < 0 || physicsCheck.touchRightWall && faceDir.x > 0) { wait = true; anim.SetBool("walk", false); } //currentState.LogicUpdate(); TimeCounter(); } public void FixedUpdate() { if(!isHurt && !isDead) { Move(); } //currentState.PhysicsUpdate(); } private void OnDisable() { // currentState.OnExit(); } public virtual void Move() { rb.velocity = new Vector2(currentSpeed * faceDir.x * Time.deltaTime, rb.velocity.y); } //计时器 public void TimeCounter() { if(wait) { waitTimeCounter -= Time.deltaTime; if(waitTimeCounter <= 0) { waitTimeCounter = waitTime; wait =false; transform.localScale = new Vector3(faceDir.x, 1, 1); //Turn(); } } } public void OnTakeDamage(Transform attackTrans) { attacker = attackTrans; if(attackTrans.position.x - transform.position.x > 0) { transform.localScale = new Vector3(-1,1,1); } if (attackTrans.position.x - transform.position.x < 0) { transform.localScale = new Vector3(1, 1, 1); } //受伤击退 isHurt = true; anim.SetTrigger("hurt"); Vector2 dir = new Vector2(transform.position.x - attackTrans.position.x, 0).normalized; StartCoroutine(OnHurt(dir)); } IEnumerator OnHurt( Vector2 dir) { rb.AddForce(hurtForce * dir, ForceMode2D.Impulse); yield return new WaitForSeconds(0.5f); isHurt = false;; } public void OnDie() { anim.SetBool("dead", true); isDead = true; Destroy(this.gameObject);//动画失效,暂时直接销毁 } public void DestroyAffterAnimation() { Destroy(this.gameObject); } /*public void Turn() { if (physicsCheck.touchLeftWall) { transform.localScale = new Vector3(-1, 1, 1); } else if (physicsCheck.touchRightWall) { transform.localScale = new Vector3(1, 1, 1); } }*/ }