主要是参考师兄的博客做的,明明很好玩的东西但自己做出来的效果不好。
public class Tank : MonoBehaviour {
private float hp =500.0f;
// 初始化
public Tank()
{
hp = 500.0f;
}
public float getHP()
{
return hp;
}
public void setHP(float hp)
{
this.hp = hp;
}
//标明子弹所属的坦克类型,TankType是枚举变量,在工厂类里MyFactory定义。
public void shoot(TankType type)
{
GameObject bullet = Singleton.Instance.getBullets(type);
bullet.transform.position = new Vector3(transform.position.x, 1.5f, transform.position.z) + transform.forward * 1.5f;
bullet.transform.forward = transform.forward; //方向
bullet.GetComponent().AddForce(bullet.transform.forward * 20, ForceMode.Impulse);
}
}
public class Player : Tank{
// player被摧毁时发布信息;
public delegate void DestroyPlayer();
public static event DestroyPlayer destroyEvent;
void Start () {
setHP(500);
}
// Update is called once per frame
void Update () {
if(getHP() <= 0) // Tank is destoryed
{
this.gameObject.SetActive(false);
destroyEvent();
}
}
//向前移动
public void moveForward()
{
gameObject.GetComponent().velocity = gameObject.transform.forward * 30;
}
//向后移动
public void moveBackWard()
{
gameObject.GetComponent().velocity = gameObject.transform.forward * -30;
}
//通过水平轴上的增量,改变玩家坦克的欧拉角,从而实现坦克转向
public void turn(float offsetX)
{
float x = gameObject.transform.localEulerAngles.x;
float y = gameObject.transform.localEulerAngles.y + offsetX*2;
gameObject.transform.localEulerAngles = new Vector3(x, y, 0);
}
}
public class Enemy : Tank {
public delegate void RecycleEnemy(GameObject enemy);
//当enemy被摧毁时,通知工厂回收;
public static event RecycleEnemy recycleEnemy;
// player 的位置
private Vector3 playerLocation;
//游戏是否结束
private bool gameover;
private void Start()
{
playerLocation = GameDirector.getInstance().currentSceneController.getPlayer().transform.position;
StartCoroutine(shoot());
}
void Update() {
playerLocation = GameDirector.getInstance().currentSceneController.getPlayer().transform.position;
gameover = GameDirector.getInstance().currentSceneController.getGameOver();
if (!gameover)
{
if (getHP() <= 0 && recycleEnemy != null)
{
recycleEnemy(this.gameObject);
}
else
{
// 自动向player移动
NavMeshAgent agent = gameObject.GetComponent();
agent.SetDestination(playerLocation);
// gameObject.transform.position = new Vector3(transform.position.x+0.01f,transform.position.y,transform.position.z);
}
}
else
{
//游戏结束,停止寻路
NavMeshAgent agent = gameObject.GetComponent();
agent.velocity = Vector3.zero;
agent.ResetPath();
}
}
// 协程实现每隔1s进行射击,开始喜欢协程了
IEnumerator shoot()
{
while (!gameover)
{
for(float i =1;i> 0; i -= Time.deltaTime)
{
yield return 0;
}
if(Vector3.Distance(playerLocation,gameObject.transform.position) < 14)
{
shoot(TankType.ENEMY);
}
}
}
}
以上就实现了这个游戏中主要角色的动作了,将player和enemy坦克都会有的属性与动作,比如血量和射击shoot放到基类Tank,减少代码的冗余并增强代码的可读性;另外,也尽量着减少与其它类的关联。
public class Bullet : MonoBehaviour {
public float explosionRadius = 3.0f;
private TankType tankType;
//设置发射子弹的坦克类型, 因为如果射到队友是不能算伤害的.
public void setTankType(TankType type)
{
tankType = type;
}
private void OnCollisionEnter(Collision collision)
{
if(collision.transform.gameObject.tag == "tankEnemy" && this.tankType == TankType.ENEMY ||
collision.transform.gameObject.tag == "tankPlayer" && this.tankType == TankType.PLAYER)
{
return;
}
MyFactory factory = Singleton.Instance;
ParticleSystem explosion = factory.getParticleSystem();
explosion.transform.position = gameObject.transform.position;
//获取爆炸范围内的所有碰撞体
Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, explosionRadius);
foreach(var collider in colliders)
{
//被击中坦克与爆炸中心的距离
float distance = Vector3.Distance(collider.transform.position, gameObject.transform.position);
float hurt;
// 如果是玩家发出的子弹伤害高一点
if (collider.tag == "tankEnemy" && this.tankType == TankType.PLAYER)
{
hurt = 300.0f / distance;
collider.GetComponent().setHP(collider.GetComponent().getHP() - hurt);
}
else if(collider.tag == "tankPlayer" && this.tankType == TankType.ENEMY)
{
hurt = 100.0f / distance;
collider.GetComponent().setHP(collider.GetComponent().getHP() - hurt);
}
explosion.Play();
}
if (gameObject.activeSelf)
{
factory.recycleBullet(gameObject);
}
}
}
//其中public的四个变量是用来在unity中将player,enemy,bullet,explosion预制拖进代码里用于实例化对象的。
//其它变量和方法应该看名称都可以看懂。
public enum TankType { PLAYER , ENEMY};
public class MyFactory : MonoBehaviour {
public GameObject player;
public GameObject enemy;
public GameObject bullet;
public ParticleSystem explosion;
private List usingTanks;
private List freeTanks;
private List usingBullets;
private List freeBullets;
private GameObject role;
private List particles;
private void Awake()
{
usingTanks = new List();
freeTanks = new List();
usingBullets = new List();
freeBullets = new List();
particles = new List();
role = GameObject.Instantiate(player) as GameObject;
role.SetActive(true);
role.transform.position = Vector3.zero;
}
// Use this for initialization
void Start () {
Enemy.recycleEnemy += recycleEnemy;
}
// Update is called once per frame
public GameObject getPlayer()
{
return role;
}
public GameObject getEnemys()
{
GameObject newTank = null;
if (freeTanks.Count <= 0)
{
newTank = GameObject.Instantiate(enemy) as GameObject;
usingTanks.Add(newTank);
newTank.transform.position = new Vector3(Random.Range(-100, 100), 0, Random.Range(-100, 100));
}
else
{
newTank = freeTanks[0];
freeTanks.RemoveAt(0);
usingTanks.Add(newTank);
}
newTank.SetActive(true);
return newTank;
}
public GameObject getBullets(TankType type)
{
GameObject newBullet;
if(freeBullets.Count <= 0)
{
newBullet = GameObject.Instantiate(bullet) as GameObject;
usingBullets.Add(newBullet);
newBullet.transform.position = new Vector3(Random.Range(-100, 100), 0, Random.Range(-100, 100));
}
else
{
newBullet = freeBullets[0];
freeBullets.RemoveAt(0);
usingBullets.Add(newBullet);
}
newBullet.GetComponent().setTankType(type);
newBullet.SetActive(true);
return newBullet;
}
public ParticleSystem getParticleSystem()
{
foreach(var particle in particles)
{
if (!particle.isPlaying)
{
return particle;
}
}
ParticleSystem newPS = GameObject.Instantiate(explosion);
particles.Add(newPS);
return newPS;
}
public void recycleEnemy(GameObject enemyTank)
{
usingTanks.Remove(enemyTank);
freeTanks.Add(enemyTank);
enemyTank.GetComponent().velocity = Vector3.zero;
enemyTank.SetActive(false);
}
public void recycleBullet(GameObject Bullet)
{
usingBullets.Remove(Bullet);
freeBullets.Add(Bullet);
Bullet.GetComponent().velocity = Vector3.zero;
Bullet.SetActive(false);
}
}
// SceneController.cs
public class SceneController : MonoBehaviour,IUserAction{
public GameObject player;
private int enemyCount = 6;
private bool gameOver = false;
private GameObject[] enemys;
private MyFactory myFactory;
public GameDirector director;
private void Awake()
{
director = GameDirector.getInstance();
director.currentSceneController = this;
enemys = new GameObject[enemyCount];
gameOver = false;
myFactory = Singleton.Instance;
}
void Start () {
player = myFactory.getPlayer();
for (int i = 0; i < enemyCount; i++)
{
enemys[i]=myFactory.getEnemys();
}
Player.destroyEvent += setGameOver;
}
// Update is called once per frame
void Update () {
Camera.main.transform.position = new Vector3(player.transform.position.x, 18, player.transform.position.z);
}
//返回玩家坦克的位置
public GameObject getPlayer()
{
return player;
}
//返回游戏状态
public bool getGameOver()
{
return gameOver;
}
//设置游戏结束
public void setGameOver()
{
gameOver = true;
}
public void moveForward()
{
player.GetComponent().moveForward();
}
public void moveBackWard()
{
player.GetComponent().moveBackWard();
}
//通过水平轴上的增量,改变玩家坦克的欧拉角,从而实现坦克转向
public void turn(float offsetX)
{
player.GetComponent().turn(offsetX);
}
public void shoot()
{
player.GetComponent().shoot(TankType.PLAYER);
}
}
//IUserAction.cs
public interface IUserAction
{
void moveForward();
void moveBackWard();
void turn(float offsetX);
void shoot();
bool getGameOver();
}
//IUserGUI.cs
public class IUserGUI : MonoBehaviour {
IUserAction action;
// Use this for initialization
void Start () {
action = GameDirector.getInstance().currentSceneController as IUserAction;
}
// Update is called once per frame
void Update () {
if (!action.getGameOver())
{
if (Input.GetKey(KeyCode.W))
{
action.moveForward();
}
if (Input.GetKey(KeyCode.S))
{
action.moveBackWard();
}
if (Input.GetKeyDown(KeyCode.Space))
{
action.shoot();
}
//获取水平轴上的增量,目的在于控制玩家坦克的转向
float offsetX = Input.GetAxis("Horizontal");
action.turn(offsetX);
}
}
void OnGUI()
{
//gameover时生成提示
if (action.getGameOver())
{
GUIStyle fontStyle = new GUIStyle();
fontStyle.fontSize = 30;
fontStyle.normal.textColor = new Color(0, 0, 0);
GUI.Button(new Rect(Screen.width/2-50, Screen.height/2-50, 200, 50), "GameOver!");
}
}
}
导演类还是和以前一样:
//GameDirector.cs
public class GameDirector : System.Object {
private static GameDirector _instance;
public SceneController currentSceneController { get; set; }
private GameDirector() { }
public static GameDirector getInstance()
{
if(_instance == null)
{
_instance = new GameDirector();
}
return _instance;
}
}
哦还有个用于产生单例的类,这个类用了泛型编程:
//Singleton.cs
public class Singleton : 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;
}
}
}