درس: حارس يقوم بدورية ويطارد

عدو يمشي في جولة ويركض نحو اللاعب إذا رآه. يعلّمك الملاحة وخط الرؤية.

1. الإعداد

الإعداد
  1. اصنع الحارس: Capsule عليها مكوّن NavAgent. تحتاج المرحلة إلى أرض يستطيع الوكيل المشي عليها؛ وللملاحة صفحة خاصة في Project Settings.
  2. أنشئ كائنات فارغة بأسماء Post 1 وPost 2 وPost 3... حيث يجب أن يقوم بالدورية. يمر السكربت عليها بالترتيب.
  3. يحتاج اللاعب إلى الوسم Player.

2. السكربت

السكربت

Scripts/Guard.cs

public class Guard : Behaviour
{
    public float sight = 12f;
    public float chaseSpeed = 5f;
    public float walkSpeed = 2f;

    GameObject player;
    bool chasing;

    public override void Start()
    {
        player = GameObject.FindPlayer();
        Round();
    }

    void Round()
    {
        var posts = new System.Collections.Generic.List<Vector3>();
        for (int n = 1; GameObject.Find("Post " + n) != null; n++) posts.Add(GameObject.Find("Post " + n).transform.position);
        gameObject.agent.speed = walkSpeed;
        if (posts.Count > 0) gameObject.agent.Patrol(posts.ToArray(), 1.5f);
        chasing = false;
    }

    public override void Update(float deltaTime)
    {
        if (player == null) return;
        Vector3 eyes = transform.position + Vector3.up * 1.6f;
        Vector3 them = player.transform.position + Vector3.up * 1f;
        // seen: near enough, and nothing but the player on the line between the two
        bool near = Vector3.Distance(eyes, them) < sight;
        bool seen = near && (!Physics.Linecast(eyes, them, out RaycastHit hit, Physics.DefaultRaycastLayers, gameObject) || hit.gameObject == player);
        if (seen)
        {
            chasing = true;
            gameObject.agent.speed = chaseSpeed;
            gameObject.agent.SetDestination(player.transform.position);
        }
        else if (chasing && gameObject.agent.arrived)
        {
            // lost them: back to the round
            Round();
        }
    }
}

احفظه باسم Scripts/Guard.cs وأضفه إلى الحارس.

3. كيف يعمل

كيف يعمل

4. جرّبه

جرّبه

امشِ خلف جدار فيفقدك الحارس. اجمعه مع الصحة: اجعل الحارس يؤذي اللاعب إذا لمسه.

التالي: برج رماية ورصاصاته.