1、改进飞碟(Hit UFO)游戏:
- 游戏内容要求:
- 按 adapter模式 设计图修改飞碟游戏
- 使它同时支持物理运动与运动学(变换)运动
采用adapter模式,所以直接在上次作业中修改代码就好了。为了将飞碟的动作变为物理运动,所以要实现一个物理动作类,代码如下:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CCPhysicmove : SSAction
{
// Use this for initialization
public float xspeed;
public override void Start()
{
if (!this.gameObject.GetComponent<Rigidbody>())
{
this.gameObject.AddComponent<Rigidbody>();
}
this.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.up*8f, ForceMode.Acceleration);
this.gameObject.GetComponent<Rigidbody>().AddForce(new Vector3(xspeed, 0, 0), ForceMode.VelocityChange);
}
private CCPhysicmove()
{
}
public static CCPhysicmove getAction(float speed){
CCPhysicmove action = CreateInstance<CCPhysicmove>();
action.xspeed = speed;
return action;
}
// Update is called once per frame
override public void Update()
{
if(transform.position.y<=3){
Destroy(this.gameObject.GetComponent<Rigidbody>());
destroy = true;
CallBack.SSActionCallback(this);
}
}
}
于之前的动作分离的方式一样,还需要一个物理动作管理类,然后由这个动作管理类使用适配器适配之前的动作管理类来完成替换,所以此时需要一个抽象接口,使两个动作管理类都继承自这个接口,然后场景就可以通过声明接口,然后自由的选择用哪种动作类了。
所以增加一个接口:
public interface IActionManager{
void MoveDisk(Disk disk);
bool IsAllFinished();
}
然后是两个动作管理类继承自该接口:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Interfaces;
public class CCPhysicmoveManager : SSActionManager,SSActionCallback ,IActionManager
{
// Use this for initialization
int count = 0;
public SSActionEventType Complete = SSActionEventType.Completed;
public void MoveDisk(Disk disk){
count++;
Complete = SSActionEventType.Started;
CCPhysicmove action = CCPhysicmove.getAction(disk.speed);
addAction(disk.gameObject, action, this);
}
public void SSActionCallback(SSAction source){
count--;
Complete = SSActionEventType.Completed;
source.gameObject.SetActive(false);
}
public bool IsAllFinished(){
if (count == 0) return true;
return false;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Interfaces;
public class CCActionManager : SSActionManager, SSActionCallback ,IActionManager
{
int count = 0;//记录所有在移动的碟子的数量
public SSActionEventType Complete = SSActionEventType.Completed;
public void MoveDisk(Disk Disk)
{
count++;
Complete = SSActionEventType.Started;
CCMoveToAction action = CCMoveToAction.getAction(Disk.speed);
addAction(Disk.gameObject, action, this);
}
public void SSActionCallback(SSAction source) //运动事件结束后的回调函数
{
count--;
Complete = SSActionEventType.Completed;
source.gameObject.SetActive(false);
}
public bool IsAllFinished() //主要为了防止游戏结束时场景还有对象但是GUI按钮已经加载出来
{
if (count == 0) return true;
else return false;
}
}
这样只需要在场景类中选择实现哪种动作类就好了:
Manager = this.gameObject.AddComponent<CCPhysicmoveManager>() as IActionManager;
这样就实现了物理运动版。
完整的项目代码: