这次的项目是弄一个牧师与恶魔的小游戏,游戏规则和背景:三个牧师和三个恶魔需要过一条河,河上只有一条船,船上最多可以载两个人,而船上最少有一个人的时候才可以开船,当六个人都到达河对岸的时候,游戏胜利,但是,当任意一边的恶魔的数目比牧师的数目多时,恶魔会攻击牧师,游戏失败。
首先,就是贴图的下载和prefab的制作,这里就不多说了。然后,成品如下:
游戏的实现采用MVC结构,全部的游戏对象和场景都由代码来实现。
首先,就从导演类开始实现,具体也没什么可说的,代码如下:
public class Director : System.Object {
private static Director _instance;
public SceneController currentSceneController { set; get; }
public static Director getInstance()
{
if(_instance == null)
{
_instance = new Director();
}
return _instance;
}
}
接下来,实现两个接口,分别是场景控制的接口和对用户动作进行反应的接口。
//游戏场景控制器
public interface SceneController {
void LoadResources();
}
public interface UserAction
{
void moveBoat();
void isClickCha(ChaController chaController);
void restart();
}
然后,就是对游戏场景中有动作的对象添加控制,在这个游戏中,有动作的对象有船(过河)、牧师(上船、上岸)和魔鬼(上船、上岸),可以看出,牧师和魔鬼的动作其实是一样的,所以,可以将他们归为同一类,就称为人类吧。之后,考虑到我们需要一个办法来判定游戏是否胜利,于是,就把两岸也当做是一个有动作的对象,他们的动作主要是判定两边的人数是否平衡,确定游戏是否结束。
为了方便处理对象的移动,这里增加多了一个类来处理物体的移动。实现如下:
//对象移动处理
public class MoveStatus : MonoBehaviour {
float speed = 15;//移动的速度
//用来检测移动的状态。由于上船或下船的时候,有两个移动段。
//0代表在开始位置,1代表从开始位置移到转折点,2代表从转折点移动到目的地
public int move_status;
//目的地的地址
Vector3 destination;
//转折点的地址
Vector3 halfDest;
private void Update()
{
//从开始移动到转折点,到转折点后,改变状态
if(move_status == 1)
{
transform.position = Vector3.MoveTowards(transform.position, halfDest, speed * Time.deltaTime);
if(transform.position == halfDest)
{
move_status = 2;
}
}
//从转折点到目的地,到目的地后,改变状态
else if(move_status == 2)
{
transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
if(transform.position == destination)
{
move_status = 0;
}
}
}
//重置移动状态
public void Reset()
{
move_status = 0;
}
//设置目的地
public void setDestination(Vector3 dest)
{
destination = dest;
move_status = 1;
//如果高度一样,证明不用经过转折点,就是,在水面上船的移动
if (dest.y == transform.position.y)
{
move_status = 2;
}
//上岸时转折处理
else if(dest.y > transform.position.y)
{
halfDest.x = transform.position.x;
halfDest.y = dest.y;
}
//上船时转折处理
else
{
halfDest.y = transform.position.y;
halfDest.x = dest.x;
}
}
}
下面就是对船这个对象的Controller,对这个对象,需要记录的就三个属性:船的移动、船上人的位置、船现在所处的位置(左边还是右边)。
先来看一下这个类的字段:
GameObject boat;//对象
MoveStatus moveable;//移动
Vector3[] from_pos;//船上的能坐人的位置,右边
Vector3[] to_pos;//船上能坐人的位置,左边
int onWhere;//标志位,船在左边还是右边(1 - 右边, -1 - 左边)
ChaController[] people = new ChaController[2];//船上的人物
由于船的移动其实就只有向左移动和向右移动,通过标志位,可以确定船要移动的方向,而船的位置移动实现可通过moveable字段来实现。如下:
/// <summary>
/// 船的移动。每移动一次,改变标志位
/// </summary>
public void Move()
{
if(onWhere == -1)
{
moveable.setDestination(new Vector3(5, 1.15f, -2.5f));
onWhere = 1;
}
else
{
moveable.setDestination(new Vector3(-5, 1.15f, -2.5f));
onWhere = -1;
}
}
其他的就是需要对船的一些状态的获取,具体类的实现如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoatController {
GameObject boat;//对象
MoveStatus moveable;//移动
Vector3[] from_pos;//船上的能坐人的位置,右边
Vector3[] to_pos;//船上能坐人的位置,左边
int onWhere;//标志位,船在左边还是右边(1 - 右边, -1 - 左边)
ChaController[] people = new ChaController[