碰撞后敌人停止追逐角色

问题描述 投票:0回答:0

我不明白为什么 MoveTowards 在 Update 中停止工作。敌人有 2 个碰撞器,一个在精灵上以造成伤害,第二个在前面用于攻击触发。而且敌人是可以远程攻击的,也就是说如果攻击动画已经开始,那么这个角色肯定会受到伤害。 EnemyAttack 绑定到动画帧

这是我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public int health;
    public float speed;
    private Animator anim;
    private float timeBtwAttack;
    public float startTimeBtwAttack;
    private Player player;
    public int damage;
    private bool isAttacking = false;

    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
    }

    // Update is called once per frame
    void Update()
    {
        if (speed == 0) 
        {
            anim.SetBool("isRunning", false);
        }
        else
        {
            anim.SetBool("isRunning", true);
        }

        if (health <= 0)
        {
            Destroy(gameObject); 
        }

        if (player.transform.position.x > transform.position.x)
            transform.eulerAngles = new Vector3(0, 0, 0);
        else
            transform.eulerAngles = new Vector3(0, 180, 0);

        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime);

        
        timeBtwAttack -= Time.deltaTime;
    }

    public void TakeDamage(int damage)
    {
        health -= damage;
    }

    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            if (timeBtwAttack <= 0 && !isAttacking)
            {
                isAttacking = true;
                anim.SetBool("attack", true);
            }
        }
    }

    public void EnemyAttack()
    {
        player.ChangeHealth(-damage);
        timeBtwAttack = startTimeBtwAttack;

        isAttacking = false;
        anim.SetBool("attack", false);
    }

    public void FinishAttack()
    {
        //isAttacking = false;
        //anim.SetBool("attack", false);
    }
}

c# unity3d
© www.soinside.com 2019 - 2024. All rights reserved.