游戏开发论坛

 找回密码
 立即注册
搜索
查看: 18435|回复: 0

技术贴:0经验上手手游Unity3D开发

[复制链接]

8360

主题

9283

帖子

2万

积分

论坛元老

Rank: 8Rank: 8

积分
29940
发表于 2015-5-13 16:53:01 | 显示全部楼层 |阅读模式
  文 / 0!1!

  现在手游火的一塌糊涂,引擎也是层出不穷除了引领3D市场的Unity3D,独霸2D市场的Cocos2D-X之外,还有虚幻、Sphinx等,甚至搜狐也开发了国产的Genesis-3D引擎。

  文章适合人群:对Unity基础组件有一些了解的,想知道怎么在项目中具体应用各种组件。

  这篇文章以一个Asset Store上面的例子“Unity Projects Stealth”来讲解Unity的一些知识。所以可能你要对Unity一些概念有个了解。

  在此之前先说下本文运行项目时的环境:

  系统 :Window 7 X64

  Unity:4.3.3f1

  1、项目大致了解

  我们打开unity,新建项目,然后导入上面下载的"Unity Projects Stealth.unitypackage"。等导入完毕后就可以看到“Project”视图(如果你没打开,可以从菜单栏“Window”-“Project”打开)里面的结构如下:

image001.png

  里面每个目录大家都可以随便打开看看:

Animations 一些角色动画
Animator 动画控制器,实际里面啥都没有-_-
Audio音频文件
Fonts字体
Gizmos在scene视图用于调试的一些图标
Materials材质
Models模型
Prefabs预设
Scenes场景文件,实际里面啥都没有-_-
Scripts脚本,实际里面啥都没有-_-
Shaders着色器
Textures一些贴图纹理
Done这里面才包含了上面缺少的动画控制器、场景文件和脚本

  大家平常做项目也可以参考上面的做法,对不同的资源放不同目录进行归类整理,而且大家一看到这些文件夹就都知道里面有什么资源。可以减少很多沟通成本,也为自己查找资源带来便利。

  好了,如果没什么问题,点击播放按钮,应该就能运行项目了。

image002.png

  使用键盘的WASD或上下左右箭头就可以控制人物走动了。屏幕左下方也有文本给出其它操作的按键。比如"Z"可以打开开关等。

  2、碰撞器基础

  一般情况下,你想让物体直接有体积,能产生碰撞,那么你需要给这个物体增加一个碰撞器“Collider”。在Unity中,你只需要选择一个对象,然后点击菜单栏的”Component“-“Physics”,里面就有各种各样的碰撞器,你根据自己模型选择一个比较接近的就OK了。Unity里面的碰撞器区分为两种,一种为静态的,另一种动态的。

  静态的意思是这个碰撞器在游戏过程中不会发生位移、旋转、缩放。

  动态的意思则是说这个碰撞器可能会在游戏过程中发生位移、旋转、缩放。动态碰撞器有两种:

  一种是CharacterController。

  另一种是普通的碰撞器+刚体组件。

  第二种一定要增加刚体组件。不然可能会导致碰撞失效、性能开销增加。(比如Unity一个UI组件NGUI,它新版本的Panel会检测当前对象是否带了Rigibody,如果没有则自动增加一个。就是为了防止开发者做一些界面动画,忘记修改添加Rigibody,导致UI按钮点击失效。)

  3、控制角色

  控制一个角色在场景中运动,最简单的做法是把一个对象拖到场景中,然后根据按键。设置这个对象transform的position值。这样对象就可以在场景中运动起来。

  获取按键可以用Input.GetAxis方法。获取X和Z轴的按键分别可以使用:Input.GetAxis("Horizontal") 和 Input.GetAxis("Vertical")方法。“Horizontal”和“Vertical”其实是在“Edit”-“Project Settings”-“Input”里面配置的。

  那么我们这个例子是使用什么方法来让玩家角色运动的呢?

  先在“Hierarchy”视图(如果没有这个视图,可以在“Window”-“Hierarchy”打开它)中找到“char_ethan”对象,选中它。

image003.png

  我们先看看它的“Inspector”视图(如果没有可以在“Window”-“Inspector”打开它)。

image004.png

  注意这里除了有基本的Transform组件外,还有“Animator”,“Capsule Collider”,“Rigidbody”组件。这三个组件其实用于做可移动物体其实是黄金组合(当然也有用“Character Controller”的)。

  还有“Audio Source”、“Audio Listener”两个分别是播放声音和监听声音的组件。

  然后"Done Player Health (Script)","Done Player Inventory (Script)","Done Player Movement (Script)"分别是对角色做控制的脚本。下面我们简单说说每个组件的用途:

  A、Animator

  其实是Unity内置的一个动画控制器,原理是状态机。比如双击上面的“Animator”面板里面的“Controller”属性:

image005.png

  就会出现状态机的编辑窗口:

image006.png

  B、Capsule Collider

  胶囊体碰撞器。比较简单,没什么好说的。

  C、Rigidbody

  刚刚上面也说了,动态碰撞器的需要。

  关于A、B、C这几个组件上面就只简单介绍到这里,这里不展开讨论。如果有需要,我后面会再单独写文章介绍。

  下面开始看看控制代码部分。

  D、DonePlayerMovement

  这里有个“DonePlayerMovement(Script)”组件,从名字上看就知道应该是控制移动的(所以说命名很重要)。我们打开这个组件的源码,看看。

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class DonePlayerMovement : MonoBehaviour  
  5. {  
  6.     public AudioClip shoutingClip;      // 玩家大喊的声音  
  7.     public float turnSmoothing = 15f;   // 用于玩家平滑转向的值  
  8.     public float speedDampTime = 0.1f;  // 用于控制从一个值变化到另一个的时间限制  
  9.       
  10.       
  11.     private Animator anim;               
  12.     private DoneHashIDs hash;           // 保存各种动画状态的hash  
  13.       
  14.       
  15.     void Awake ()  
  16.     {  
  17.         anim = GetComponent<Animator>();  
  18.         hash = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneHashIDs>();  
  19.          
  20.         // Set the weight of the shouting layer to 1.  
  21.         anim.SetLayerWeight(1, 1f);  
  22.     }  
  23.       
  24.       
  25.     void FixedUpdate ()  
  26.     {  
  27.         // Cache the inputs.  
  28.         float h = Input.GetAxis("Horizontal");  
  29.         float v = Input.GetAxis("Vertical");  
  30.         bool sneak = Input.GetButton("Sneak");  
  31.          
  32.         MovementManagement(h, v, sneak);  
  33.     }  
  34.       
  35.       
  36.     void Update ()  
  37.     {  
  38.         // Cache the attention attracting input.  
  39.         bool shout = Input.GetButtonDown("Attract");  
  40.          
  41.         // Set the animator shouting parameter.  
  42.         anim.SetBool(hash.shoutingBool, shout);  
  43.          
  44.         AudioManagement(shout);  
  45.     }  
  46.       
  47.       
  48.     void MovementManagement (float horizontal, float vertical, bool sneaking)  
  49.     {  
  50.         // Set the sneaking parameter to the sneak input.  
  51.         anim.SetBool(hash.sneakingBool, sneaking);  
  52.          
  53.         // If there is some axis input...  
  54.         if(horizontal != 0f || vertical != 0f)  
  55.         {  
  56.             // ... set the players rotation and set the speed parameter to 5.5f.  
  57.             Rotating(horizontal, vertical);  
  58.             anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);  
  59.         }  
  60.         else  
  61.             // Otherwise set the speed parameter to 0.  
  62.             anim.SetFloat(hash.speedFloat, 0);  
  63.     }  
  64.       
  65.       
  66.     void Rotating (float horizontal, float vertical)  
  67.     {  
  68.         // Create a new vector of the horizontal and vertical inputs.  
  69.         Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);  
  70.          
  71.         // Create a rotation based on this new vector assuming that up is the global y axis.  
  72.         Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);  
  73.          
  74.         // Create a rotation that is an increment closer to the target rotation from the player's rotation.  
  75.         Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);  
  76.          
  77.         // Change the players rotation to this new rotation.  
  78.         rigidbody.MoveRotation(newRotation);  
  79.     }  
  80.       
  81.       
  82.     void AudioManagement (bool shout)  
  83.     {  
  84.         // If the player is currently in the run state...  
  85.         if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.locomotionState)  
  86.         {  
  87.             // ... and if the footsteps are not playing...  
  88.             if(!audio.isPlaying)  
  89.                 // ... play them.  
  90.                 audio.Play();  
  91.         }  
  92.         else  
  93.             // Otherwise stop the footsteps.  
  94.             audio.Stop();  
  95.          
  96.         // If the shout input has been pressed...  
  97.         if(shout)  
  98.             // ... play the shouting clip where we are.  
  99.             AudioSource.PlayClipAtPoint(shoutingClip, transform.position);  
  100.     }  
  101. }  
复制代码

  这个脚本整体来说:

  在Awake的时候,先找到脚本需要用到的Animator组件和DoneHashIds组件,然后缓存它们(在后面用到就不需要频繁查找了,节省CPU)。

  在FixedUpdate的时候,获取玩家按下的移动键,并处理移动、角色朝向问题。

  在Update的时候,获取玩家是否按下“Attract”键,并确定是否播放动画以及声音。

  OK,我们主要来看看MovementManagement这个方法:

  1. void MovementManagement (float horizontal, float vertical, bool sneaking)  
  2. {  
  3.     // Set the sneaking parameter to the sneak input.  
  4.     anim.SetBool(hash.sneakingBool, sneaking);  
  5.       
  6.     // If there is some axis input...  
  7.     if(horizontal != 0f || vertical != 0f)  
  8.     {  
  9.         // ... set the players rotation and set the speed parameter to 5.5f.  
  10.         Rotating(horizontal, vertical);  
  11.         anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);  
  12.     }  
  13.     else  
  14.         // Otherwise set the speed parameter to 0.  
  15.         anim.SetFloat(hash.speedFloat, 0);  
  16. }  
复制代码

  我们可以发现,除了Rotating方法,基本都是对anim做一些状态设置的方法。那么Rotating方法里面是什么呢?

  1. void Rotating (float horizontal, float vertical)  
  2. {  
  3.     // 创建一个Vector3用于保存输入的水平位移方向  
  4.     Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);  
  5.       
  6.     // 根据上面的方向计算这个方向指向的角度  
  7.     Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);  
  8.       
  9.     // 创建一个从玩家当前方向旋转到目标方向的旋转增量  
  10.     Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);  
  11.       
  12.     // 修改玩家的方向  
  13.     rigidbody.MoveRotation(newRotation);  
  14. }  
复制代码

  代码没有实现玩家的位置移动的代码,但是实际运行的时候却可以看到角色会移动。这是为什么?

  我们一起看到“Hierarchy”视图中的“char_ethan”。注意里面的Animator组件(它勾选了“Apply Root Motion”):

image008.png

  我们看到官方文档对于这个选项是这么介绍的:Root motion is the effect where an object's entire mesh moves away from its starting point but that motion is created by the animation itself rather than by changing the Transform position.

  这里大致的意思其实就是:这个选项会在由动画产生移动时,使得物体的mesh会偏离起点。那也就是物体的移动是做在动画中的,然后勾选Animator的ApplyRootMotion选项来实现的。

  关于角色控制中anim.SetFloat的方法的,这个涉及到动画混合,我们在这里暂时不讲。

  那么角色的移动、旋转就都讲了。接下来我们看看碰撞器。

  4、碰撞器及其使用

  前面我们说了碰撞器分静态和动态两种。

  那么角色“char_ethan”身上的肯定就是动态碰撞器了,注意到“char_ethan”对象有个“Capsule Collider”组件。这就是一个胶囊体碰撞器组件。然后角色还有个“rigidbody”组件,这个是刚体组件。也就是采用前面说的普通碰撞器+刚体组件。

  关于各种内置碰撞器的知识。大家不了解的可以看看官网http://docs.unity3d.com/Manual/Physics3DReference.html(我不会告诉你我大部分U3D的知识都在官网学习的。)

  这里只要知道碰撞器一个重要的选项“Is Trigger”

image009.png

  只要两个相互碰撞的碰撞器,有任何一个勾选了IsTrigger,那么就会触发这两个碰撞器上面的OnTriggerEnter方法。如果两个相互碰撞的碰撞器,都没勾选IsTrigger,那么会触发这两个碰撞器上面的OnCollisionEnter,OnCollisionStay,OnCollisionExit方法。

  只有在不勾选IsTrigger的时候,才能使用Physics.Raycast进行射线检测。所以当你的碰撞方法没有调用的时候,请确保IsTrigger和方法是符合的。

  注意:这个游戏中玩家走路的时候不会穿墙,因为墙的碰撞器和玩家身上的碰撞器都没有勾选IsTrigger。

  5、怪物AI

  在“Hierarchy”视图中找到三个怪物“char_robotGuard_001”、“char_robotGuard_002”、“char_robotGuard_003”,这三个怪物上面的组件其实都是一样的。我们来看看“char_robotGuard_001”就可以了。看看怪物是怎么巡逻、然后发现敌人进行追踪的。

  怪物身上有如下组件:

image010.png

  A、Animator

  这里不再赘述。

  B、碰撞器

  两个碰撞器?为什么这里要用两个碰撞器?我们先看看两个碰撞器的属性:

image011.png

  一个是胶囊体,没有勾选IsTrigger。这个应该是配合走路,为了不让角色穿过建筑物的。

  第二个是球体碰撞器,勾选了IsTrigger。干嘛用的,别急,我们还是先来看那4个脚本吧。

  C、DoneEnemySight

  二话不说我们先上代码:

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class DoneEnemySight : MonoBehaviour  
  5. {  
  6.     public float fieldOfViewAngle = 110f;               // Number of degrees, centred on forward, for the enemy see.  
  7.     public bool playerInSight;                          // Whether or not the player is currently sighted.  
  8.     public Vector3 personalLastSighting;                // Last place this enemy spotted the player.  
  9.       
  10.       
  11.     private NavMeshAgent nav;                           // Reference to the NavMeshAgent component.  
  12.     private SphereCollider col;                         // Reference to the sphere collider trigger component.  
  13.     private Animator anim;                              // Reference to the Animator.  
  14.     private DoneLastPlayerSighting lastPlayerSighting;  // Reference to last global sighting of the player.  
  15.     private GameObject player;                          // Reference to the player.  
  16.     private Animator playerAnim;                        // Reference to the player's animator component.  
  17.     private DonePlayerHealth playerHealth;              // Reference to the player's health script.  
  18.     private DoneHashIDs hash;                           // Reference to the HashIDs.  
  19.     private Vector3 previousSighting;                   // Where the player was sighted last frame.  
  20.       
  21.       
  22.     void Awake ()  
  23.     {  
  24.         // Setting up the references.  
  25.         nav = GetComponent<NavMeshAgent>();  
  26.         col = GetComponent<SphereCollider>();  
  27.         anim = GetComponent<Animator>();  
  28.         lastPlayerSighting = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneLastPlayerSighting>();  
  29.         player = GameObject.FindGameObjectWithTag(DoneTags.player);  
  30.         playerAnim = player.GetComponent<Animator>();  
  31.         playerHealth = player.GetComponent<DonePlayerHealth>();  
  32.         hash = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneHashIDs>();  
  33.          
  34.         // Set the personal sighting and the previous sighting to the reset position.  
  35.         personalLastSighting = lastPlayerSighting.resetPosition;  
  36.         previousSighting = lastPlayerSighting.resetPosition;  
  37.     }  
  38.       
  39.       
  40.     void Update ()  
  41.     {  
  42.         // If the last global sighting of the player has changed...  
  43.         if(lastPlayerSighting.position != previousSighting)  
  44.             // ... then update the personal sighting to be the same as the global sighting.  
  45.             personalLastSighting = lastPlayerSighting.position;  
  46.          
  47.         // Set the previous sighting to the be the sighting from this frame.  
  48.         previousSighting = lastPlayerSighting.position;  
  49.          
  50.         // If the player is alive...  
  51.         if(playerHealth.health > 0f)  
  52.             // ... set the animator parameter to whether the player is in sight or not.  
  53.             anim.SetBool(hash.playerInSightBool, playerInSight);  
  54.         else  
  55.             // ... set the animator parameter to false.  
  56.             anim.SetBool(hash.playerInSightBool, false);  
  57.     }  
  58.       
  59.   
  60.     void OnTriggerStay (Collider other)  
  61.     {  
  62.         // If the player has entered the trigger sphere...  
  63.         if(other.gameObject == player)  
  64.         {  
  65.             // By default the player is not in sight.  
  66.             playerInSight = false;  
  67.               
  68.             // Create a vector from the enemy to the player and store the angle between it and forward.  
  69.             Vector3 direction = other.transform.position - transform.position;  
  70.             float angle = Vector3.Angle(direction, transform.forward);  
  71.               
  72.             // If the angle between forward and where the player is, is less than half the angle of view...  
  73.             if(angle < fieldOfViewAngle * 0.5f)  
  74.             {  
  75.                 RaycastHit hit;  
  76.                   
  77.                 // ... and if a raycast towards the player hits something...  
  78.                 if(Physics.Raycast(transform.position + transform.up, direction.normalized, out hit, col.radius))  
  79.                 {  
  80.                     // ... and if the raycast hits the player...  
  81.                     if(hit.collider.gameObject == player)  
  82.                     {  
  83.                         // ... the player is in sight.  
  84.                         playerInSight = true;  
  85.                           
  86.                         // Set the last global sighting is the players current position.  
  87.                         lastPlayerSighting.position = player.transform.position;  
  88.                     }  
  89.                 }  
  90.             }  
  91.               
  92.             // Store the name hashes of the current states.  
  93.             int playerLayerZeroStateHash = playerAnim.GetCurrentAnimatorStateInfo(0).nameHash;  
  94.             int playerLayerOneStateHash = playerAnim.GetCurrentAnimatorStateInfo(1).nameHash;  
  95.               
  96.             // If the player is running or is attracting attention...  
  97.             if(playerLayerZeroStateHash == hash.locomotionState || playerLayerOneStateHash == hash.shoutState)  
  98.             {  
  99.                 // ... and if the player is within hearing range...  
  100.                 if(CalculatePathLength(player.transform.position) <= col.radius)  
  101.                     // ... set the last personal sighting of the player to the player's current position.  
  102.                     personalLastSighting = player.transform.position;  
  103.             }  
  104.         }  
  105.     }  
  106.       
  107.       
  108.     void OnTriggerExit (Collider other)  
  109.     {  
  110.         // If the player leaves the trigger zone...  
  111.         if(other.gameObject == player)  
  112.             // ... the player is not in sight.  
  113.             playerInSight = false;  
  114.     }  
  115.       
  116.       
  117.     float CalculatePathLength (Vector3 targetPosition)  
  118.     {  
  119.         // Create a path and set it based on a target position.  
  120.         NavMeshPath path = new NavMeshPath();  
  121.         if(nav.enabled)  
  122.             nav.CalculatePath(targetPosition, path);  
  123.          
  124.         // Create an array of points which is the length of the number of corners in the path + 2.  
  125.         Vector3 [] allWayPoints = new Vector3[path.corners.Length + 2];  
  126.          
  127.         // The first point is the enemy's position.  
  128.         allWayPoints[0] = transform.position;  
  129.          
  130.         // The last point is the target position.  
  131.         allWayPoints[allWayPoints.Length - 1] = targetPosition;  
  132.          
  133.         // The points inbetween are the corners of the path.  
  134.         for(int i = 0; i < path.corners.Length; i++)  
  135.         {  
  136.             allWayPoints[i + 1] = path.corners[i];  
  137.         }  
  138.          
  139.         // Create a float to store the path length that is by default 0.  
  140.         float pathLength = 0;  
  141.          
  142.         // Increment the path length by an amount equal to the distance between each waypoint and the next.  
  143.         for(int i = 0; i < allWayPoints.Length - 1; i++)  
  144.         {  
  145.             pathLength += Vector3.Distance(allWayPoints[i], allWayPoints[i + 1]);  
  146.         }  
  147.          
  148.         return pathLength;  
  149.     }  
  150. }  
复制代码

Awake主要是获取一些组件,在后面的逻辑中可以使用。
Update检查玩家最后一次被发现的位置是否一致,不是则同步位置。
把playerInSight(是否发现玩家)这个状态设置到Animator的状态机里面。
OnTriggerStay没错,前面说到的第二个碰撞器正是这里要用到的。第二个碰撞器勾选了IsTrigger,就是为了触发这个方法。
当玩家进入这个碰撞器(也就是怪物的视野)触发。
检查玩家是否在怪物前方,而且玩家和怪物中间没有遮挡物。那么设置playerInSight为true。
OnTriggerExit当玩家离开怪物的视野(碰撞器)。那么设置playerInSight为false。
CalculatePathLength计算怪物和玩家当前的距离。

  基本这个组件就是用于检测玩家是否在怪物视野内。然后设置玩家的一些位置信息,以及是否被发现的信息。

  我们接着看DoneEnemyAI这个组件

  D、DoneEnemyAI

  还是上代码:

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class DoneEnemyAI : MonoBehaviour  
  5. {  
  6.     public float patrolSpeed = 2f;                          // The nav mesh agent's speed when patrolling.  
  7.     public float chaseSpeed = 5f;                           // The nav mesh agent's speed when chasing.  
  8.     public float chaseWaitTime = 5f;                        // The amount of time to wait when the last sighting is reached.  
  9.     public float patrolWaitTime = 1f;                       // The amount of time to wait when the patrol way point is reached.  
  10.     public Transform[] patrolWayPoints;                     // An array of transforms for the patrol route.  
  11.       
  12.       
  13.     private DoneEnemySight enemySight;                      // Reference to the EnemySight script.  
  14.     private NavMeshAgent nav;                               // Reference to the nav mesh agent.  
  15.     private Transform player;                               // Reference to the player's transform.  
  16.     private DonePlayerHealth playerHealth;                  // Reference to the PlayerHealth script.  
  17.     private DoneLastPlayerSighting lastPlayerSighting;      // Reference to the last global sighting of the player.  
  18.     private float chaseTimer;                               // A timer for the chaseWaitTime.  
  19.     private float patrolTimer;                              // A timer for the patrolWaitTime.  
  20.     private int wayPointIndex;                              // A counter for the way point array.  
  21.       
  22.       
  23.     void Awake ()  
  24.     {  
  25.         // Setting up the references.  
  26.         enemySight = GetComponent<DoneEnemySight>();  
  27.         nav = GetComponent<NavMeshAgent>();  
  28.         player = GameObject.FindGameObjectWithTag(DoneTags.player).transform;  
  29.         playerHealth = player.GetComponent<DonePlayerHealth>();  
  30.         lastPlayerSighting = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneLastPlayerSighting>();  
  31.     }  
  32.       
  33.       
  34.     void Update ()  
  35.     {  
  36.         // If the player is in sight and is alive...  
  37.         if(enemySight.playerInSight && playerHealth.health > 0f)  
  38.             // ... shoot.  
  39.             Shooting();  
  40.          
  41.         // If the player has been sighted and isn't dead...  
  42.         else if(enemySight.personalLastSighting != lastPlayerSighting.resetPosition && playerHealth.health > 0f)  
  43.             // ... chase.  
  44.             Chasing();  
  45.          
  46.         // Otherwise...  
  47.         else  
  48.             // ... patrol.  
  49.             Patrolling();  
  50.     }  
  51.       
  52.       
  53.     void Shooting ()  
  54.     {  
  55.         // Stop the enemy where it is.  
  56.         nav.Stop();  
  57.     }  
  58.       
  59.       
  60.     void Chasing ()  
  61.     {  
  62.         // Create a vector from the enemy to the last sighting of the player.  
  63.         Vector3 sightingDeltaPos = enemySight.personalLastSighting - transform.position;  
  64.          
  65.         // If the the last personal sighting of the player is not close...  
  66.         if(sightingDeltaPos.sqrMagnitude > 4f)  
  67.             // ... set the destination for the NavMeshAgent to the last personal sighting of the player.  
  68.             nav.destination = enemySight.personalLastSighting;  
  69.          
  70.         // Set the appropriate speed for the NavMeshAgent.  
  71.         nav.speed = chaseSpeed;  
  72.          
  73.         // If near the last personal sighting...  
  74.         if(nav.remainingDistance < nav.stoppingDistance)  
  75.         {  
  76.             // ... increment the timer.  
  77.             chaseTimer += Time.deltaTime;  
  78.               
  79.             // If the timer exceeds the wait time...  
  80.             if(chaseTimer >= chaseWaitTime)  
  81.             {  
  82.                 // ... reset last global sighting, the last personal sighting and the timer.  
  83.                 lastPlayerSighting.position = lastPlayerSighting.resetPosition;  
  84.                 enemySight.personalLastSighting = lastPlayerSighting.resetPosition;  
  85.                 chaseTimer = 0f;  
  86.             }  
  87.         }  
  88.         else  
  89.             // If not near the last sighting personal sighting of the player, reset the timer.  
  90.             chaseTimer = 0f;  
  91.     }  
  92.   
  93.       
  94.     void Patrolling ()  
  95.     {  
  96.         // Set an appropriate speed for the NavMeshAgent.  
  97.         nav.speed = patrolSpeed;  
  98.          
  99.         // If near the next waypoint or there is no destination...  
  100.         if(nav.destination == lastPlayerSighting.resetPosition || nav.remainingDistance < nav.stoppingDistance)  
  101.         {  
  102.             // ... increment the timer.  
  103.             patrolTimer += Time.deltaTime;  
  104.               
  105.             // If the timer exceeds the wait time...  
  106.             if(patrolTimer >= patrolWaitTime)  
  107.             {  
  108.                 // ... increment the wayPointIndex.  
  109.                 if(wayPointIndex == patrolWayPoints.Length - 1)  
  110.                     wayPointIndex = 0;  
  111.                 else  
  112.                     wayPointIndex++;  
  113.                   
  114.                 // Reset the timer.  
  115.                 patrolTimer = 0;  
  116.             }  
  117.         }  
  118.         else  
  119.             // If not near a destination, reset the timer.  
  120.             patrolTimer = 0;  
  121.          
  122.         // Set the destination to the patrolWayPoint.  
  123.         nav.destination = patrolWayPoints[wayPointIndex].position;  
  124.     }  
  125. }  
复制代码

  这个组件主要是:如果判断玩家在视野中,则对玩家进行射击。如果玩家最后一次被发现的点不是默认点,则进行追击。否则就进行巡逻。

  追击、巡逻,主要都是对NavMeshAgent进行设置来实现控制怪物的移动。关于NavMeshAgent我们以后再专门来讲解。

  而射击调用的Shooting方法里面只有一行代码:nav.Stop。那么射击具体在哪里实现的?接着看DoneEnemyShooting组件。

  E、DoneEnemyShooting

  看代码:

  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class DoneEnemyShooting : MonoBehaviour  
  5. {  
  6.     public float maximumDamage = 120f;                  // The maximum potential damage per shot.  
  7.     public float minimumDamage = 45f;                   // The minimum potential damage per shot.  
  8.     public AudioClip shotClip;                          // An audio clip to play when a shot happens.  
  9.     public float flashIntensity = 3f;                   // The intensity of the light when the shot happens.  
  10.     public float fadeSpeed = 10f;                       // How fast the light will fade after the shot.  
  11.       
  12.       
  13.     private Animator anim;                              // Reference to the animator.  
  14.     private DoneHashIDs hash;                           // Reference to the HashIDs script.  
  15.     private LineRenderer laserShotLine;                 // Reference to the laser shot line renderer.  
  16.     private Light laserShotLight;                       // Reference to the laser shot light.  
  17.     private SphereCollider col;                         // Reference to the sphere collider.  
  18.     private Transform player;                           // Reference to the player's transform.  
  19.     private DonePlayerHealth playerHealth;              // Reference to the player's health.  
  20.     private bool shooting;                              // A bool to say whether or not the enemy is currently shooting.  
  21.     private float scaledDamage;                         // Amount of damage that is scaled by the distance from the player.  
  22.       
  23.       
  24.     void Awake ()  
  25.     {  
  26.         // Setting up the references.  
  27.         anim = GetComponent<Animator>();  
  28.         laserShotLine = GetComponentInChildren<LineRenderer>();  
  29.         laserShotLight = laserShotLine.gameObject.light;  
  30.         col = GetComponent<SphereCollider>();  
  31.         player = GameObject.FindGameObjectWithTag(DoneTags.player).transform;  
  32.         playerHealth = player.gameObject.GetComponent<DonePlayerHealth>();  
  33.         hash = GameObject.FindGameObjectWithTag(DoneTags.gameController).GetComponent<DoneHashIDs>();  
  34.          
  35.         // The line renderer and light are off to start.  
  36.         laserShotLine.enabled = false;  
  37.         laserShotLight.intensity = 0f;  
  38.          
  39.         // The scaledDamage is the difference between the maximum and the minimum damage.  
  40.         scaledDamage = maximumDamage - minimumDamage;  
  41.     }  
  42.       
  43.       
  44.     void Update ()  
  45.     {  
  46.         // Cache the current value of the shot curve.  
  47.         float shot = anim.GetFloat(hash.shotFloat);  
  48.          
  49.         // If the shot curve is peaking and the enemy is not currently shooting...  
  50.         if(shot > 0.5f && !shooting)  
  51.             // ... shoot  
  52.             Shoot();  
  53.          
  54.         // If the shot curve is no longer peaking...  
  55.         if(shot < 0.5f)  
  56.         {  
  57.             // ... the enemy is no longer shooting and disable the line renderer.  
  58.             shooting = false;  
  59.             laserShotLine.enabled = false;  
  60.         }  
  61.          
  62.         // Fade the light out.  
  63.         laserShotLight.intensity = Mathf.Lerp(laserShotLight.intensity, 0f, fadeSpeed * Time.deltaTime);  
  64.     }  
  65.       
  66.       
  67.     void OnAnimatorIK (int layerIndex)  
  68.     {  
  69.         // Cache the current value of the AimWeight curve.  
  70.         float aimWeight = anim.GetFloat(hash.aimWeightFloat);  
  71.          
  72.         // Set the IK position of the right hand to the player's centre.  
  73.         anim.SetIKPosition(AvatarIKGoal.RightHand, player.position + Vector3.up * 1.5f);  
  74.          
  75.         // Set the weight of the IK compared to animation to that of the curve.  
  76.         anim.SetIKPositionWeight(AvatarIKGoal.RightHand, aimWeight);  
  77.     }  
  78.       
  79.       
  80.     void Shoot ()  
  81.     {  
  82.         // The enemy is shooting.  
  83.         shooting = true;  
  84.          
  85.         // The fractional distance from the player, 1 is next to the player, 0 is the player is at the extent of the sphere collider.  
  86.         float fractionalDistance = (col.radius - Vector3.Distance(transform.position, player.position)) / col.radius;  
  87.       
  88.         // The damage is the scaled damage, scaled by the fractional distance, plus the minimum damage.  
  89.         float damage = scaledDamage * fractionalDistance + minimumDamage;  
  90.   
  91.         // The player takes damage.  
  92.         playerHealth.TakeDamage(damage);  
  93.          
  94.         // Display the shot effects.  
  95.         ShotEffects();  
  96.     }  
  97.       
  98.       
  99.     void ShotEffects ()  
  100.     {  
  101.         // Set the initial position of the line renderer to the position of the muzzle.  
  102.         laserShotLine.SetPosition(0, laserShotLine.transform.position);  
  103.          
  104.         // Set the end position of the player's centre of mass.  
  105.         laserShotLine.SetPosition(1, player.position + Vector3.up * 1.5f);  
  106.          
  107.         // Turn on the line renderer.  
  108.         laserShotLine.enabled = true;  
  109.          
  110.         // Make the light flash.  
  111.         laserShotLight.intensity = flashIntensity;  
  112.          
  113.         // Play the gun shot clip at the position of the muzzle flare.  
  114.         AudioSource.PlayClipAtPoint(shotClip, laserShotLight.transform.position);  
  115.     }  
  116. }  
复制代码


  Update的时候可以发现它检查动画的shotFloat属性。然后判断是否应该射击或取消射击。而射击的激光,这里可以看到是采用LineRenderer实现的。

  6、事件通知

  以上关于怪物的AI我们就讲完了。但这只是单个怪物的AI。实际这个游戏里面还有用于监控玩家的摄像头、还有红外线墙检测玩家是否通过。但是原理都一样。都是通过监听碰撞器的OnTriggerStay来设置玩家被发现的全局位置。也就是DoneLastPlayerSighting。

  个人关于这个demo代码设计的看法:

  我个人觉得这种做法不好。大家都自己去获取DoneLastPlayerSighting,然后自己检查里面的状态。然后还可以设置里面的状态。这样会导致程序变量跟踪困难。

  如果是我的话,我会把DoneLastPlayerSighting做成是一个消息中心。然后每个敌人订阅这个消息中心的消息(即玩家被发现的位置发生变化的消息),然后由消息中心通知所有订阅的对象。然后订阅的对象也可以提交自己发现的目标给消息中心,如果消息中心确认通过,再通知已经订阅的其它对象。这样做起来代码会更清晰,更容易维护。

  7、渲染特效

  A、雾效

  你可以通过点击Unity的菜单栏“Edit”-“Render Settings”。这时候在右边的Inspector面板可以通过勾选“fog”选项来开启雾效。“Fog Color”可以调整雾的颜色。

  B、游戏中监视器投射到地上的亮点

  在“Hiererchy”中找到监视器物体“prop_cctvCam_001”,你会发现它下面有个子物体“cam_frustum_collision”,它上面有个Light组件,Light上的Cookie属性就是产生亮点的贴图。

  C、激光墙的激光

  其实就是用了一个"Self-Illumin/Diffuse"的shader,这是一个自发光shader,你可以尝试一下,在相同的灯光条件下,采用自发光shader的物体总会比Diffuse的亮。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2024-4-27 12:21

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表