3D游戏编程与设计——模型与动画章节作业与练习
作业与练习
智能巡逻兵
- 提交要求:
- 游戏设计要求:
- 创建一个地图和若干巡逻兵(使用动画);
- 每个巡逻兵走一个3~5个边的凸多边型,位置数据是相对地址。即每次确定下一个目标位置,用自己当前位置为原点计算;
- 巡逻兵碰撞到障碍物,则会自动选下一个点为目标;
- 巡逻兵在设定范围内感知到玩家,会自动追击玩家;
- 失去玩家目标后,继续巡逻;
- 计分:玩家每次甩掉一个巡逻兵计一分,与巡逻兵碰撞游戏结束;
- 程序设计要求:
- 必须使用订阅与发布模式传消息
- subject:OnLostGoal
- Publisher: ?
- Subscriber: ?
- 工厂模式生产巡逻兵
- 必须使用订阅与发布模式传消息
- 友善提示1:生成 3~5个边的凸多边型
- 随机生成矩形
- 在矩形每个边上随机找点,可得到 3 - 4 的凸多边型
- 5 ?
- 友善提示2:参考以前博客,给出自己新玩法
游戏玩法设计
在一副地图里面,有若干个区域,每个区域有一个巡逻兵与一个水晶体,此外还有一个玩家,当玩家进入特定区域之后,当前区域的巡逻兵会朝向玩家前进,若巡逻兵碰到了玩家,玩家就会死掉,玩家的任务是在躲避巡逻兵的情况下,收拾掉地图上全部水晶,即可获得胜利。
项目结构
本次项目使用到了动作分离、MVC模式、工厂模式、订阅与发表模式。
结构如下:
- Script:
- ActionController:
- BasicActionController:
- CCMoveToAction.cs
- CCTracertAction.cs
- SSAction.cs
- SSActionManager.cs
- CCActionManager.cs
- BasicActionController:
- Collide:
- AreaCollide.cs
- CollectCollide.cs
- PlayerCollide.cs
- GameObjects:
- Prop:
- Prop.cs
- PropFactory.cs
- Prop:
- GUI:
- InterfaceGUI.cs
- SceneControllers:
- FirstSceneController.cs
- GameEventManager.cs
- Interface.cs
- Singleton.cs
- SSDirector.cs
- ActionController:
具体各个脚本文件的含义留到代码详解部分解释
预制体
需要三个预制体,分别是玩家、巡逻兵、地图。
巡逻兵制作:
巡逻兵预制体使用了StoneMonster
第三方资源:
首先给该对象设置刚体和碰撞器,并把PlayerCollide脚本拖入:
其次,还需要设置该对象的Animator:
创建一个Animator controller如下,并拖入到该对象的Animator属性中。
其中两个Parameters分别控制是巡逻状态还是攻击状态。
此外,使用资源包中的animations时候,记得设置animation type 为generic,如课上讲的那样。
玩家制作:
与巡逻兵制作类似,西安则了TailedFox
资源包:
给该对象设置刚体和碰撞器:
其次,还需要设置该对象的Animator:
创建一个Animator controller如下,并拖入到该对象的Animator属性中。
除此之外,还需要添加InterfaceGUI脚本到camera中,并把camera添加为玩家的子对象,实现跟随视角。
地图制作:
使用到了AxeyWorks
资源包:
与之前作业制作地图那次相似,制作一个地图预制体即可。
代码详解
- CCMoveToAction.cs
创建一个“从一个位置移动到另一个位置”的通用动作。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CCMoveToAction : SSAction
{
public Vector3 target; // 目标位置
public float speed; // 移动速度
public int block; // 块号
private CCMoveToAction() { }
// 返回一个MoveTo动作
public static CCMoveToAction getAction(int block, float speed, Vector3 position)
{
CCMoveToAction action = ScriptableObject.CreateInstance<CCMoveToAction>();
action.target = position;
action.speed = speed;
action.block = block;
return action;
}
// 更新
public override void Update()
{
// 若已经到达了目标位置,删除该动作
if (this.transform.position == target)
{
destroy = true;
CallBack.SSActionCallback(this);
}
// 更新新的位置
this.transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
public override void Start()
{
// 设置转向
Quaternion rotation = Quaternion.LookRotation(target - transform.position, Vector3.up);
transform.rotation = rotation;
}
}
- CCTracertAction.cs
创建一个“跟踪对象”的通用动作。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CCTracertAction : SSAction
{
public GameObject target; // 目标对象
public float speed; // 移动速度
private CCTracertAction() { }
// 返回一个Tracert动作
public static CCTracertAction getAction(GameObject target, float speed)
{
CCTracertAction action = ScriptableObject.CreateInstance<CCTracertAction>();
action.target = target;
action.speed = speed;
return action;
}
public override void Update()
{
this.transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime);
Quaternion rotation = Quaternion.LookRotation(target.transform.position - gameObject.transform.position, Vector3.up);
gameObject.transform.rotation = rotation;
// 撞到了目标物或者脱离范围了,则删除此动作
if (gameObject.GetComponent<Prop>().follow_player == false || transform.position == target.transform.position)
{
destroy = true;
CallBack.SSActionCallback(this);
}
}
public override void Start()
{
}
}
- SSAction.cs
通用动作基类。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class SSAction : ScriptableObject
{
public bool enable = true;
public bool destroy = false;
public GameObject gameObject;
public Transform transform;
public SSActionCallback CallBack;
public virtual void Start()
{
throw new System.NotImplementedException();
}
public virtual void Update()
{
throw new System.NotImplementedException();
}
}
- SSActionManager.cs
动作管理者基类。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class SSActionManager : MonoBehaviour
{
// 动作集
private Dictionary<int, SSAction> actions = new Dictionary<int, SSAction>();
// 等待被加入的动作(动作即将开始)
private List<SSAction> waitingToAdd = new List<SSAction>();
// 等待被删除的动作(动作已经完成)
private List<int> watingToDelete = new List<int>();
// 更新上面三个集合的状态
protected void Update()
{
// 将等待被加入的动作加入到动作集中
foreach (SSAction ac in waitingToAdd)
{
actions[ac.GetInstanceID()] = ac;
}
waitingToAdd.Clear();
// 将已经完成的动作移除动作集,加入到等待被删除的动作集中,否则更新该动作。
foreach (KeyValuePair<int, SSAction> kv in actions)
{
SSAction ac = kv.Value;
if (ac.destroy)
{
watingToDelete.Add(ac.GetInstanceID());
}
else if (ac.enable)
{
ac.Update();
}
}
// 将动作集中要被删除的动作删除掉
foreach (int key in watingToDelete)
{
SSAction ac = actions[key];
actions.Remove(key);
DestroyObject(ac);
}
watingToDelete.Clear();
}
// 添加动作
public void addAction(GameObject gameObject, SSAction action, SSActionCallback ICallBack)
{
action.gameObject = gameObject;
action.transform = gameObject.transform;
action.CallBack = ICallBack;
waitingToAdd.Add(action);
action.Start();
}
}
- CCActionManager.cs
动作管理者,主要是为传入的对象添加动作。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class CCActionManager : SSActionManager, SSActionCallback
{
public SSActionEventType Complete = SSActionEventType.Completed;
Dictionary<int, CCMoveToAction> actionList = new Dictionary<int, CCMoveToAction>();
// 跟随玩家
public void Tracert(GameObject p, GameObject player)
{
if (actionList.ContainsKey(p.GetComponent<Prop>().block)) actionList[p.GetComponent<Prop>().block].destroy = true;
CCTracertAction action = CCTracertAction.getAction(player, 0.8f);
addAction(p.gameObject, action, this);
}
// 绕圈行走
public void GoAround(GameObject p)
{
CCMoveToAction action = CCMoveToAction.getAction(p.GetComponent<Prop>().block, 0.6f, GetNewTarget(p));
actionList.Add(p.GetComponent<Prop>().block, action);
addAction(p.gameObject, action, this);
}
// 绕圈行走中获得新的目标位置
private Vector3 GetNewTarget(GameObject p)
{
Vector3 pos = p.transform.position;
int block = p.GetComponent<Prop>().block;
float ZUp = 13.2f - (block / 3) * 9.65f;
float ZDown = 5.5f - (block / 3) * 9.44f;
float XUp = -4.7f + (block % 3) * 8.8f;
float XDown = -13.3f + (block % 3) * 10.1f;
Vector3 Move = new Vector3(Random.Range(-2f, 2f), 0, Random.Range(-2f, 2f));
Vector3 Next = pos + Move;
while (!(Next.x < XUp && Next.x > XDown && Next.z < ZUp && Next.z > ZDown))
{
Move = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));
Next = pos + Move;
}
return Next;
}
// 停止所有动作
public void StopAll()
{
foreach (CCMoveToAction x in actionList.Values)
{
x.destroy = true;
}
actionList.Clear();
}
// 回调函数
public void SSActionCallback(SSAction source)
{
if (actionList.ContainsKey(source.gameObject.GetComponent<Prop>().block)) actionList.Remove(source.gameObject.GetComponent<Prop>().block);
GoAround(source.gameObject);
}
}
- AreaCollide.cs
玩家进入新区域,发布对应事件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AreaCollide : MonoBehaviour
{
public int sign = 0;
FirstSceneController sceneController;
private void Start()
{
sceneController = SSDirector.getInstance().currentScenceController as FirstSceneController;
}
void OnTriggerEnter(Collider collider)
{
// 标记玩家进入自己的区域
if (collider.gameObject.tag == "Player")
{
sceneController.SetPlayerArea(sign);
GameEventManager.Instance.PlayerEscape();
}
}
}
- CollectCollide.cs
玩家获得水晶(碰撞)。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectCollide : MonoBehaviour
{
void OnCollisionEnter(Collision other)
{
SSDirector director;
// 当玩家与水晶相撞
if (other.gameObject.tag == "Player")
{
Destroy(this.gameObject);
director = SSDirector.getInstance();
int i = director.currentScenceController.GetCollector();
i = i + 1;
director.currentScenceController.setCollect(i);
}
}
}
- PlayerCollide.cs
巡逻兵发生碰撞,若是碰到玩家,则发布游戏结束事件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollide : MonoBehaviour
{
void OnCollisionEnter(Collision other)
{
// 当玩家与侦察兵相撞
if (other.gameObject.tag == "Player")
{
GameEventManager.Instance.PlayerGameover();
}
}
}
- Prop.cs
巡逻兵数据对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Prop : MonoBehaviour
{
public int block;
public bool follow_player = false;
private void Start()
{
if (gameObject.GetComponent<Rigidbody>())
{
gameObject.GetComponent<Rigidbody>().freezeRotation = true;
}
}
void Update()
{
if (this.gameObject.transform.localEulerAngles.x != 0 || gameObject.transform.localEulerAngles.z != 0)
{
gameObject.transform.localEulerAngles = new Vector3(0, gameObject.transform.localEulerAngles.y, 0);
}
if (gameObject.transform.position.y != 0)
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x, 0, gameObject.transform.position.z);
}
}
}
- PropFactory.cs
工厂模式生产巡逻兵
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PropFactory
{
public static PropFactory PF = new PropFactory();
private Dictionary<int, GameObject> used = new Dictionary<int, GameObject>();
private PropFactory()
{
}
int[] pos_x = { -7, 0, 7 };
int[] pos_z = { 8, 2, -8 };
public Dictionary<int, GameObject> GetProp()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
GameObject newProp = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/Prop"));
newProp.AddComponent<Prop>();
newProp.transform.position = new Vector3(pos_x[j], 0, pos_z[i]);
newProp.GetComponent<Prop>().block = i * 3 + j;
newProp.SetActive(true);
used.Add(i * 3 + j, newProp);
}
}
return used;
}
public void StopPatrol()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
used[i * 3 + j].transform.position = new Vector3(pos_x[j], 0, pos_z[i]);
}
}
}
}
- InterfaceGUI.cs
初始化游戏画面中的Text标志以及获得用户键盘输入。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
using UnityEngine.UI;
public class InterfaceGUI : MonoBehaviour
{
UserAction UserActionController;
ISceneController SceneController;
CCActionManager CCManger;
public GameObject t;
bool ss = false;
bool win = false;
float S;
PropFactory PF;
void Start()
{
UserActionController = SSDirector.getInstance().currentScenceController as UserAction;
SceneController = SSDirector.getInstance().currentScenceController as ISceneController;
S = Time.time;
}
private void OnGUI()
{
if (!ss) S = Time.time;
GUI.Label(new Rect(0, 30, 75, 30), "Crystal: " + SceneController.GetCollector().ToString());
GUI.Label(new Rect(Screen.width - 160, 30, 150, 30), "Score: " + UserActionController.GetScore().ToString() + " Time: " + ((int)(Time.time - S)).ToString());
if (ss)
{
if (!UserActionController.GetGameState())
{
ss = false;
}
if (SceneController.GetCollector() >= 9)
{
win = true;
ss = false;
}
}
else
{
if (win)
{
GUIStyle fontStyle = new GUIStyle();
fontStyle.alignment = TextAnchor.MiddleCenter;
fontStyle.fontSize = 25;
fontStyle.normal.textColor = Color.white;
GUI.Label(new Rect(Screen.width / 2 - 25, Screen.height / 2 - 80, 100, 50), "WINNER!", fontStyle);
PF = PropFactory.PF;
PF.StopPatrol();
if (GUI.Button(new Rect(Screen.width / 2 - 30, Screen.height / 2 - 30, 100, 50), "EXIT"))
{
UnityEditor.EditorApplication.isPlaying = false;
}
}
else if (GUI.Button(new Rect(Screen.width / 2 - 30, Screen.height / 2 - 30, 100, 50), "Start"))
{
ss = true;
SceneController.LoadResources();
S = Time.time;
UserActionController.Restart();
}
}
}
private void Update()
{
// 获取方向键的偏移量
float translationX = Input.GetAxis("Horizontal");
float translationZ = Input.GetAxis("Vertical");
// 移动玩家
UserActionController.MovePlayer(translationX, translationZ);
}
}
- FirstSceneController.cs
游戏场景控制器。
场景控制器是订阅者,在初始化时将自身相应的事件处理函数提交给消息处理器,在相应事件发生时被自动调用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class FirstSceneController : MonoBehaviour, ISceneController, UserAction
{
GameObject player = null;
PropFactory PF;
int score = 0;
int PlayerArea = 4;
bool gameState = false;
int collector = 0;
Dictionary<int, GameObject> allProp = null;
CCActionManager CCManager = null;
public void setCollect(int collect)
{
collector = collect;
}
public int GetCollector()
{
return collector;
}
void Awake()
{
SSDirector director = SSDirector.getInstance();
director.currentScenceController = this;
PF = PropFactory.PF;
if(CCManager == null)
{
CCManager = gameObject.AddComponent<CCActionManager>();
}
if(player == null && allProp == null)
{
Instantiate(Resources.Load<GameObject>("Prefabs/Plane"), new Vector3(0, 0, 0), Quaternion.identity);
player = Instantiate(Resources.Load("Prefabs/Player"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
allProp = PF.GetProp();
}
if (player.GetComponent<Rigidbody>())
{
player.GetComponent<Rigidbody>().freezeRotation = true;
}
}
void Update()
{
if (player.transform.localEulerAngles.x != 0 || player.transform.localEulerAngles.z != 0)
{
player.transform.localEulerAngles = new Vector3(0, player.transform.localEulerAngles.y, 0);
}
if (player.transform.position.y <= 0)
{
player.transform.position = new Vector3(player.transform.position.x, 0, player.transform.position.z);
}
}
void OnEnable()
{
GameEventManager.ScoreChange += AddScore;
GameEventManager.GameoverChange += Gameover;
}
void OnDisable()
{
GameEventManager.ScoreChange -= AddScore;
GameEventManager.GameoverChange -= Gameover;
}
public void LoadResources()
{
}
public int GetScore()
{
return score;
}
public void Restart()
{
player.GetComponent<Animator>().Play("idle");
PF.StopPatrol();
gameState = true;
score = 0;
player.transform.position = new Vector3(0, 0, 0);
allProp[PlayerArea].GetComponent<Prop>().follow_player = true;
CCManager.Tracert(allProp[PlayerArea], player);
foreach (GameObject x in allProp.Values)
{
if (!x.GetComponent<Prop>().follow_player)
{
CCManager.GoAround(x);
}
}
}
public bool GetGameState()
{
return gameState;
}
public void SetPlayerArea(int x)
{
if (PlayerArea != x && gameState)
{
allProp[PlayerArea].GetComponent<Animator>().SetBool("run", false);
allProp[PlayerArea].GetComponent<Prop>().follow_player = false;
PlayerArea = x;
}
}
void AddScore()
{
if (gameState)
{
++score;
allProp[PlayerArea].GetComponent<Prop>().follow_player = true;
CCManager.Tracert(allProp[PlayerArea], player);
allProp[PlayerArea].GetComponent<Animator>().SetBool("run", true);
}
}
void Gameover()
{
CCManager.StopAll();
allProp[PlayerArea].GetComponent<Prop>().follow_player = false;
allProp[PlayerArea].GetComponent<Animator>().SetTrigger("attack");
player.GetComponent<Animator>().SetTrigger("death");
gameState = false;
}
public void MovePlayer(float translationX, float translationZ)
{
if (gameState && player != null)
{
if (translationZ != 0)
{
player.GetComponent<Animator>().SetBool("run", true);
}
else
{
player.GetComponent<Animator>().SetBool("run", false);
}
player.transform.Translate(0, 0, translationZ * 4f * Time.deltaTime);
player.transform.Rotate(0, translationX * 50f * Time.deltaTime, 0);
}
}
}
- GameEventManager.cs
游戏事件管理器。订阅与发布模式中的中继者,消息的订阅者通过与管理器中相应的事件委托绑定,在管理器响应的函数被发布者调用(也就是发布者发布相应消息时),订阅者绑定的相应事件处理函数也会被调用。订阅与发布模式实现了一部分消息的发布者和订阅者之间的解耦,让发布者和订阅者不必产生直接联系。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameEventManager
{
public static GameEventManager Instance = new GameEventManager();
// 计分
public delegate void ScoreEvent();
public static event ScoreEvent ScoreChange;
// 游戏结束
public delegate void GameoverEvent();
public static event GameoverEvent GameoverChange;
private GameEventManager() { }
// 玩家逃脱
public void PlayerEscape()
{
if(ScoreChange != null)
{
ScoreChange();
}
}
// 玩家被捕
public void PlayerGameover()
{
if(GameoverChange != null)
{
GameoverChange();
}
}
}
- Interface.cs
公用接口
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Interfaces
{
public interface ISceneController
{
void setCollect(int collect);
int GetCollector();
void LoadResources();
}
public interface UserAction
{
int GetScore();
void Restart();
bool GetGameState();
void MovePlayer(float translationX, float translationZ);
}
public enum SSActionEventType : int { Started, Completed }
public interface SSActionCallback
{
void SSActionCallback(SSAction source);
}
}
- Singleton.cs
单例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
protected static T instance;
public static T Instance
{
get
{
if(instance == null)
{
instance = (T)FindObjectOfType(typeof(T));
if(instance == null)
{
Debug.LogError("An instance of " + typeof(T) + " is needed in the scene, but there is none. ");
}
}
return instance;
}
}
}
- SSDirector.cs
导演
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class SSDirector : System.Object
{
private static SSDirector _instance;
public ISceneController currentScenceController { get; set; }
public bool running { get; set; }
public static SSDirector getInstance()
{
if(_instance == null)
{
_instance = new SSDirector();
}
return _instance;
}
public int getFPS()
{
return Application.targetFrameRate;
}
public void setFPS(int fps)
{
Application.targetFrameRate = fps;
}
}
项目运行
创建空对象,将FirstSceneController脚本拖入,运行。
视频中有更长的游戏过程。