- 游戏内容参照这里
- 这里我的游戏基本框架参照MokHoYin的博客,细节方面有些不同
- 游戏效果展示:方块代表巡逻兵,圆球代表玩家,其中巡逻兵在自己对应的矩形中巡逻。
- GameModel.cs
这里定义的游戏对象PatrolInstance,PlayerInstance,backgroundInstance,uiInstance是我们做好的预制,分别用来实例化巡逻兵、玩家、背景以及UI。在实现巡逻兵的巡逻时,每次都让巡逻兵往向一个方向移动随机的距离。若撞到围栏或者这段距离移动结束,就转一个方向继续巡逻。每次Update时都要检测玩家在哪个区域上,一方面好通知这一区域的巡逻兵去追逐玩家,另一方面,若是玩家逃离了一个巡逻兵的追逐,则可以让玩家得分。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Com.Patrols;
public class GameModel : SSActionManager, ISSActionCallback {
//运行之前将预制拖入这些属性中
public GameObject PatrolInstance, PlayerInstance, backgroundInstance, uiInstance;
private SceneController scene;
private GameObject zyzPlayer, background, gameText;
//巡逻兵对象列表
private List<GameObject> PatrolList;
//巡逻兵巡逻的方向
private List<int> PatrolDirection;
//巡逻兵的巡逻速度
private const float NORMAL_SPEED = 0.5f;
//巡逻兵追逐玩家时的速度
private const float CHASING_SPEED = 0.7f;
void Awake() {
//用一个预制初始化工厂中用于生产巡逻兵的对象
PatrolFactory.getInstance().initPatrolInatance(PatrolInstance);
}
protected new void Start () {
scene = SceneController.getInstance();
scene.setGameModel(this);
//生产玩家(同样是用之前做好的预制)
createPlayer();
//用工厂制作6个巡逻兵
createPatrols();
//背景
background = Instantiate(backgroundInstance);
gameText = Instantiate(uiInstance);
}
protected new void Update() {
base.Update();
}
void createPlayer() {
zyzPlayer = Instantiate(PlayerInstance);
}
void createPatrols() {
PatrolList = new List<GameObject>(6);
PatrolDirection = new List<int>(6);
Vector3[] locations = PatrolFactory.getInstance().getPatrolLocations();
for (int i = 0; i < 6; i++) {
//使用工厂模式初始化游戏对象
GameObject newPatrol = PatrolFactory.getInstance().getPatrol();
newPatrol.transform.position = locations[i];
newPatrol.name = "Patrol" + i;
//初始化巡逻方向为空
PatrolDirection.Add(-2);
PatrolList.Add