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合併後的程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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<cameraraycaster>();
   character = GetComponent<thirdpersoncharacter> ();
 
   agent = GetComponent<navmeshagent> ();
   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<navmeshagent> ().stoppingDistance = walkMoveStopRadius;
   }
  }
 
  void OnMouseOverEnemy(Enemy enemy){
   if (Input.GetMouseButton (0)) {
    // 設置地點為Enemy的位置
    agent.SetDestination(enemy.transform.position);
    GetComponent<navmeshagent> ().stoppingDistance = attackMoveStopRadius;
   }
  }
 
  void OnDrawGizmos(){
   //繪製攻擊範圍
   Gizmos.color = new Color(255f, 0f, 0f, 0.5f);
   Gizmos.DrawWireSphere (transform.position, attackMoveStopRadius);
  }
 }
}
 
</navmeshagent></navmeshagent></navmeshagent></thirdpersoncharacter></cameraraycaster>


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

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

留言