己方的飞机控制已经初步完成了,现在要加入敌机了。

理论上应该有两种方式:

1.预先设定,就是在编辑器里在你想要的位置上加上敌方的攻击单位

2.动态生成,根据游戏进行的时间来控制敌方攻击单位的产生。

 

这边采用第2个方式来产生,有一些地面单位倒是可以用第一种方式来产生。

 

我们首先要设置一个敌机的产生位置,用空的object可以随意的定一个坐标。

using UnityEngine;
using System.Collections;

public class EnemyManager : MonoBehaviour {

public GameObject m_EnemyPre;
public Transform m_CreatePoint;

//一波飞机的数量
public const int MAX_GROUP_ENEMYS = 4;
//两波飞机之间的时间间隔
public float GROUP_INTERVAL = 2.0f;
//同一波中两架飞机之间产生的间隔
public float CREATE_INTERVAL = 0.25f;

private float m_fTimeAfterOneGroup = 0.0f;
private float m_fTimeAfterCreate = 0.0f;
private int m_nEnemyNum = 0;


// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void Update ()
{
m_fTimeAfterOneGroup +=Time.deltaTime;
m_fTimeAfterCreate += Time.deltaTime;

if (m_fTimeAfterOneGroup > 2.0f)
{
if (m_fTimeAfterCreate > 0.25f)
{
GameObject clone = (GameObject)Instantiate(m_EnemyPre,
m_CreatePoint.position, m_CreatePoint.rotation);

clone.AddComponent("MoveScript_Shake");
m_nEnemyNum +=1;
m_fTimeAfterCreate = 0;
}

if (m_nEnemyNum == MAX_GROUP_ENEMYS)
{
m_fTimeAfterOneGroup = 0.0f;
m_nEnemyNum = 0;
}
}
}
}

 

敌机的移动脚本,可自己再定义新的移动脚本,在创建新敌机时挂上去就好:

using UnityEngine;
using System.Collections;

public class MoveScript_Shake : MonoBehaviour {

//标志左右移动方向
private int m_nDir = 1;
//原始位置
private Vector3 m_OriginalPos;
//水平移动速度
public float m_HoriSpeed = 0.1f;
//翻转速度
public float m_RotSpeed = 1.0f;
//向前移动速度
public float m_MoveSpeed = 0.0005f;

public Vector3 curScreenPos;

public Vector3 LDPoint;

// Use this for initialization
void Start ()
{
m_OriginalPos = transform.position;
LDPoint = GameObject.Find("LDPoint").transform.position;
print (LDPoint);
}

// Update is called once per frame
void Update ()
{
float relativeOffset = transform.position.x - m_OriginalPos.x;

if (Mathf.Abs(relativeOffset) > 5)
{
m_nDir = -m_nDir;
}

transform.Translate(new Vector3(m_nDir * m_HoriSpeed, 0, m_MoveSpeed));

Transform planeTrans = transform.GetChild(0).transform;
planeTrans.Rotate(0.0f, 0.0f, -m_nDir * m_RotSpeed);


//出屏则消除
// curScreenPos = Camera.mainCamera.WorldToScreenPoint(transform.position);
//print("Cur:"+curScreenPos);
if (transform.position.z < Camera.mainCamera.transform.position.z - 10)
{
Destroy(this.gameObject);
}
// print("Cur:"+transform.position);
// if (transform.position.z < LDPoint.z)
// {
// Destroy(this.gameObject);
// }
}
}


实现效果: