如何让GameObject停止?

时间:2018-05-27 20:27:56

标签: c# unity3d

我为敌人AI制作了这个简单的脚本。我希望敌人在他攻击时停止旋转并向我们移动。我怎么写呢? 代码在下面。

using System.Collections;
using UnityEngine;

public class Chasev2 : MonoBehaviour {

    public Transform Player;
    public float Attack_range=8.5f;
    public float Chase_range=50.0f; //How far ahead the enenmy can see
    public float Distance;
    public float rotation_speed=10.0f;
    private Animator anim;
    public float move_speed=10.0f;


    // Use this for initialization
    void Start () {
        anim = GetComponent<Animator> ();
    }

    // Update is called once per frame
    void Update () {
        anim.SetBool ("Run", true);
        anim.SetBool ("Idle", false);
        anim.SetBool ("Attack", false);
        Distance = (Player.transform.position - transform.position).magnitude;
        if (Distance <= Chase_range && Distance > Attack_range)
        {
            Vector3 Direction = Player.position - transform.position;
            Direction.y = 0;
            transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (Direction), rotation_speed * Time.deltaTime);
            transform.eulerAngles = new Vector3 (0, transform.eulerAngles.y, 0);
            transform.position += transform.forward * move_speed * Time.deltaTime;
        }
        else
        {
            anim.SetBool ("Run", false);
            anim.SetBool ("Idle", true);
            anim.SetBool ("Attack", false);
        }
        if (Distance < Attack_range)
        {
            anim.SetBool ("Run", false);
            anim.SetBool ("Attack", true);
            anim.SetBool ("Idle", false);
        }
    }


void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
            Gizmos.DrawWireSphere (transform.position,Attack_range);

        Gizmos.color = Color.yellow;
            Gizmos.DrawWireSphere (transform.position,Chase_range);

    }
}

1 个答案:

答案 0 :(得分:0)

现在无法对此进行真正的测试,但请尝试将攻击范围条件设置为else。

像这样:

'if (Distance <= Chase_range && Distance > Attack_range)
{
    Vector3 Direction = Player.position - transform.position;
    Direction.y = 0;
    transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (Direction), rotation_speed * Time.deltaTime);
    transform.eulerAngles = new Vector3 (0, transform.eulerAngles.y, 0);
    transform.position += transform.forward * move_speed * Time.deltaTime;
}
else if (Distance < Attack_range)
{
    anim.SetBool ("Run", false);
    anim.SetBool ("Attack", true);
    anim.SetBool ("Idle", false);
}
else
{
    anim.SetBool ("Run", false);
    anim.SetBool ("Idle", true);
    anim.SetBool ("Attack", false);
}

`

我建议你学习如何使用FSM让你的AI更容易和更清洁;)