using UnityEngine;
using System.Collections; public class Tank : MonoBehaviour { //坦克面积结构体对象
public TankArea tankArea;
private float hor, ver;
//坦克行走的速度,以及掉头速度
public float moveSpeed = ;
public float turnSpeed = ; void Start()
{
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical"); }
void Update()
{
//t坦克转身
hor = Input.GetAxis("Horizontal");
transform.eulerAngles += hor * Vector3.up * turnSpeed;
//坦克前后行进
ver = Input.GetAxis("Vertical");
transform.position += transform.right * ver * Time.deltaTime * moveSpeed; //实时同步坦克面积结构体对象
tankArea.TankInit (transform.position.x, transform.position.z);
}
}
有了坦克之后再创造敌军坦克,随机生成并且向主坦克进攻。没有创造发射子弹以及敌人消失功能
using UnityEngine;
using System.Collections;
using System.Collections.Generic; public class EnemyCreater : MonoBehaviour { //敌方坦克预设体
public GameObject enemyPrefab;
//场面上的所有坦克
private List<Tank> allTank;
//主角坦克
private Tank playerArea;
//计时器
private float timer;
//生成坦克的时间间隔
public float interval = ; void Awake()
{
allTank = new List<Tank> ();
} void Start()
{
//找到主角TankArea对象
playerArea = GameObject.FindWithTag ("Player").
GetComponent<Tank> ();
//将主角坦克添加到列表中
allTank.Add (playerArea);
} void Update()
{
//计时器计时
timer += Time.deltaTime;
//计时结束
if (timer >= interval) {
///TODO:生成坦克
EnemyInit();
//计时器清零
timer = ;
}
} /// <summary>
/// 生成坦克
/// </summary>
void EnemyInit()
{
//随机位置
float currentX;
float currentZ;
do {
//开始随机
currentX = Random.Range (-23.0f, 23.0f);
currentZ = Random.Range (-23.0f, 23.0f);
} while (!EnemyCheck(currentX,currentZ));
//可用位置
Vector3 canUsePos = new Vector3(currentX,,currentZ);
//生成
GameObject current = Instantiate (enemyPrefab,
canUsePos,
Quaternion.identity) as GameObject;
//更新当前坦克列表
allTank.Add (current.GetComponent<Tank> ());
} /// <summary>
/// 坦克位置检测
/// </summary>
/// <returns>True为可用,false为不可用.</returns>
/// <param name="x">The x .</param>
/// <param name="z">The z .</param>
bool EnemyCheck(float x,float z)
{
//遍历所有坦克
foreach (var currentT in allTank) {
//检测当前坦克位置是否与该范围冲突
bool canUse = !currentT.tankArea.PositionCheck (new Vector3 (x, , z));
//如果冲突
if (!canUse)
//返回不可用
return false;
}
//返回可用
return true;
}
} 需要引用的TankArea脚本
using UnityEngine;
using System.Collections; public struct TankArea
{
//坦克坐标
Vector2 position;
//左下坐标
public Vector2 leftDown;
//右上坐标
public Vector2 rightUp; public void TankInit(float x,float z)
{
//设置坦克位置
position = new Vector2 (x,z);
//生成左上及右下点坐标
leftDown = new Vector2 (x-,z-2.7f);
rightUp = new Vector2 (x+,z+4.2f);
} /// <summary>
/// 位置检测
/// </summary>
/// <returns>如果该位置在范围内返回True,否则返回false</returns>
/// <param name="pos">传入的坦克位置.</param>
public bool PositionCheck(Vector3 pos)
{
if (pos.x > leftDown.x
&& pos.x < rightUp.x
&& pos.z > leftDown.y
&& pos.z < rightUp.y) {
return true;
}
return false;
}
}