Related Posts Plugin for WordPress, Blogger...

4-4 Eliminate AICharacterControl

今天繼續來重構!這次要簡化AICharacterControl,請大家先注意本篇文章的重構會導致Enemy暫時無法追蹤玩家,不過沒關係,因為本次重構計畫將Player與Enemy相似的部分程式碼合併,所以後續的文章會再補上這個功能,就請一直跟著每篇文章進行重構吧。

首先請將Player中的PlayerMovement.cs改名為CharacterMovement.cs,這要讓Player跟Enemy都共用。更名完成後,應該會發現Player中原本的元件寫著Nothing Selected,就請放心的移除他吧。

AI Character Control這個元件,也同樣放心的移除吧!

然後,下列是將AICharacterControl與CharacterMovement合併後的程式碼:

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

namespace RPG.Character{
 [RequireComponent(typeof (NavMeshAgent))]
 [RequireComponent(typeof (ThirdPersonCharacter))]
 public class CharacterMovement : MonoBehaviour
 {
  [SerializeField] float walkMoveStopRadius = 0.2f;
  [SerializeField] float attackMoveStopRadius = 5f;

  ThirdPersonCharacter character = null;
  NavMeshAgent agent = null;

     private void Start()
     {
   CameraRaycaster cameraRaycaster = Camera.main.GetComponent();
   character = GetComponent ();

   agent = GetComponent ();
   agent.updateRotation = false;
   agent.updatePosition = true;

   cameraRaycaster.onMouseOverWalkable += OnMouseOverWalkable;
   cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
     }

  void Update(){
   if (agent.remainingDistance > agent.stoppingDistance) {
    character.Move(agent.desiredVelocity, false, false);
   } else {
    character.Move (Vector3.zero, false, false);
   }
  }

  void OnMouseOverWalkable(Vector3 destination){
   if (Input.GetMouseButton (0)) {
    // 設置地點為滑鼠點擊的位置
    agent.SetDestination(destination);
    GetComponent ().stoppingDistance = walkMoveStopRadius;
   }
  }

  void OnMouseOverEnemy(Enemy enemy){
   if (Input.GetMouseButton (0)) {
    // 設置地點為Enemy的位置
    agent.SetDestination(enemy.transform.position);
    GetComponent ().stoppingDistance = attackMoveStopRadius;
   }
  }

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



接著,請將CharacterMovement.cs拉入Player。

將專案中的AICharacterControl移除吧!請執行遊戲看看確認可以正確移動玩家角色,但是Enemy會暫時無法追蹤,於後續的文章再來繼續改善。

留言