Related Posts Plugin for WordPress, Blogger...

2-12 Player Pathfinding To Enemies

本章要介紹製作Player走到Enemy面前的方法,大家可以參考2-9 Make Enemies Pathfind To Player 

基本上,原理是一樣的,所以就不多做額外的說明啦!首先,當然要將Player新增Nav Mesh Agent跟AI Character Control兩個組件。

再來修改PlayerMovement.cs,其原理大致上是建立一個Empty GameObject名為WalkTarget,然後將WalkTarget設置到偵測滑鼠點擊的位置,並由Nav Mesh Agent自動導航到此處。相比過去舊的寫法,這方式可以自動尋徑繞過建築物。

接著程式碼上菜!註解自己看吧!

using System;
using UnityEngine;
using UnityEngine.AI;
using UnityStandardAssets.Characters.ThirdPerson;

[RequireComponent(typeof (NavMeshAgent))]
[RequireComponent(typeof (AICharacterControl))]
[RequireComponent(typeof (ThirdPersonCharacter))]
public class PlayerMovement : MonoBehaviour
{
 [SerializeField] float walkMoveStopRadius = 0.2f;
 [SerializeField] float attackMoveStopRadius = 5f;

    ThirdPersonCharacter theThirdPersonCharacter = null;
    CameraRaycaster cameraRaycaster = null;
    Vector3 clickPoint;
    AICharacterControl aiCharacterControl = null;
    GameObject walkTarget = null;

    private void Start()
    {
        cameraRaycaster = Camera.main.GetComponent();
        theThirdPersonCharacter = GetComponent();
        aiCharacterControl = GetComponent ();
        // 自動在場景中新增GameObject
        walkTarget = new GameObject ("WalkTarget");

        cameraRaycaster.notifyMouseClickObservers += ProcessMouseMovement;
    }

    private void ProcessMouseMovement(RaycastHit raycastHit, int layerHit){
        const int walkable = 8, enemy = 9;
        switch (layerHit) {
        case walkable:
         // 取得滑鼠點擊到的位置,並把WalkTarget設置在那裡
         walkTarget.transform.position = raycastHit.point;
         // 追蹤WalkTarget
         aiCharacterControl.SetTarget (walkTarget.transform);
         GetComponent ().stoppingDistance = walkMoveStopRadius;
         break;
        case enemy:
         // 取得滑鼠點擊到的GameObject
         GameObject enemyObejct = raycastHit.collider.gameObject;
         // 追蹤Enemy
         aiCharacterControl.SetTarget (enemyObejct.transform);
         GetComponent ().stoppingDistance = attackMoveStopRadius;
         break;
        default:
         print ("Unexpected layer found.");
         break;
        }

    }

    void OnDrawGizmos(){
        //繪製移動路徑
        Gizmos.color = Color.black;
        Gizmos.DrawLine (transform.position, clickPoint);
        Gizmos.DrawSphere (clickPoint, 0.1f);

        //繪製攻擊範圍
        Gizmos.color = new Color(255f, 0f, 0f, 0.5f);
        Gizmos.DrawWireSphere (transform.position, attackMoveStopRadius);
    }
}


留言