生成敌人
构想是在方块中间3*3区域随机生成,因为生成是放在update里的,不能让他疯狂生成,要加条件
于是想把生成条件设为player每次落地时,那么就不能连续移动,必须等player停在墙上先。
在上一章的move.cs里面添加一个状态码,初始值为2,在判断里加上rdy ==0,并且在飞行时设为rdy=1
public static int rdy = 2;//设置player状态:2(落地),1(飞行中),0(待发射)
if (Input.GetMouseButtonDown(0) && rdy==0 )
{
rb2D.velocity = direction * movespeed;
rdy = 1;
}
那碰撞到墙也要加入rdy=2
private void OnCollisionEnter2D(Collision2D collision)//碰撞器检测函数
{
//Debug.Log(collision.gameObject.tag);
if (collision.gameObject.tag == "wall" )
{
Vector2 tp = rb2D.velocity;
//撞墙停止
rb2D.velocity = tp.normalized * 0f;
rdy = 2;
//效果不好,注释掉
//rb2D.velocity = Vector2.zero;
}
}
制作了一个敌人预置体

加了一个碰撞盒,把is trigger勾上,想法是能穿过它

要在每次点击鼠标都增加一次times记录游戏流程
生成数量则设置成一个2为底的对数,能让敌人数量随着游戏流程逐渐变多。
public class enemy : MonoBehaviour
{
//预制体生成
//次数
//敌人数量
//敌人最大数量
public GameObject[] EnemyPrefab;
int times = 0;
int enemyAmount = 1;
int maxenemy = 11;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
enemyproduce();
//Debug.Log(times+";"+enemyAmount);//控制台显示次数与敌人数量
}
void enemyproduce()//生成敌人
{
//生成条件为player落地
if (move.rdy == 2)
{
//生成敌人数量
for (int i = 0; i < enemyAmount; i++)
{
enemyrandom();
}
//状态设为待发射
//生成次数
//生成敌人的数量为log2为底times+1的对数
move.rdy = 0;
times++;
if (enemyAmount < maxenemy) {
enemyAmount = Mathf.FloorToInt(Mathf.Log(times + 1, 2));
}
}
}//生成敌人end
当然,我的player碰到了就要摧毁
OnTriggerEnter2D 触发器
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "enemy")
{
Destroy(collision.gameObject);
}
}
效果

飞过去之后↓生成新的,旧的消失











