改进飞碟(Hit UFO)游戏
- 游戏内容要求:
- 按 adapter模式 设计图修改飞碟游戏
- 使它同时支持物理运动与运动学(变换)运动
UML图
实现思路
使用满足物理运动学的原理来实现飞碟的移动即可,再假设不存在任何阻力的情况下,飞碟在飞行时只会受到重力,物体在某一加速度方向上的位移公式为vt+at^2/2,根据此公式实现位移即可
游戏规则:每轮会扔出十个飞碟,回合数不限,飞碟飞出的速度会随着回合数的提高而提高;当飞碟飞出视野则扣除1点血量,血量为0时游戏结束,若回合结束后血量>0则自动进入下一回合;
计分规则:飞碟颜色对应分值+飞碟速度分值*飞碟大小分值
具体代码
UFOData.cs
保存在飞碟上的组件,储存着飞碟相关数值
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UFOData : MonoBehaviour{
public int score; //飞碟分数
public int angle; //飞碟飞出角度
public float speed; //初始速度
public Color color; //飞碟颜色
public Vector3 pos; //飞碟位置
public Vector3 scale; //飞碟大小
}
UFOFactory.cs
飞碟的回收工厂,用于生产和回收飞碟,飞碟的各项随机属性也在工厂中实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UFOFactory : MonoBehaviour {
public GameObject ufo; //飞碟实例
private List<UFOData> used = new List<UFOData>(); //使用中的飞碟
private Queue<UFOData> free = new Queue<UFOData>(); //空闲的飞碟
private void Awake() {
ufo = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Prefabs/ufo"), Vector3.zero, Quaternion.identity);
ufo.SetActive(false);
}
//得到一个飞碟,参数round用于计算当前关卡飞碟速度
public GameObject getUFO(int round) {
GameObject need = null; //用于返回的游戏对象
Color color; //飞碟的颜色
int color_choice = Random.Range(0, 3); //决定飞碟的颜色
int side = Random.Range(0, 2); //飞碟从屏幕左右侧飞出
int angle = Random.Range(0, 21); //飞碟飞出角度
int score; //不同颜色对应的分值
int scale = Random.Range(2, 5); //飞碟大小
float y = Random.Range(4f, 6f);
if (free.Count > 0) //有空闲飞碟直接使用
need = free.Dequeue().gameObject;
else { //没有就生成新的游戏对象
need = GameObject.Instantiate<GameObject>(ufo, Vector3.zero, Quaternion.identity);
need.AddComponent<UFOData>();
}
if (color_choice == 0) {
color = Color.red;
score = 1;
}
else if (color_choice == 1) {
color = Color.blue;
score = 2;
}
else {
color = Color.green;
score = 3;
}
need.GetComponent<UFOData>().speed = 2 * round + 2f;
need.GetComponent<UFOData>().color = color;
need.GetComponent<UFOData>().scale = new Vector3(scale / 4f, 0.05f, scale / 4f);
need.GetComponent<UFOData>().score = score + (round + 1) * (5 - scale);
if (side == 0) {
need.GetCompon