游戏场景——敌人——移动的敌人
制作预制体
将坦克拖拽至场景中进行设置
写代码
让坦克在两点之间不停移动
随机坐标函数
然后在start()中调用即可
坦克要一直盯着玩家
当小于一定距离时,攻击玩家
重写开火逻辑
注意还要将其tag改成Monster!
当敌人死亡后,增加分数
重写死亡逻辑
最后再为敌人添加死亡特效即可
直到当前MonsterTank的代码为:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterTank : TankBaseObj
{
//坦克移动的目标地点
public Transform targetPos;
//坦克的随机坐标位置(在unity中进行关联)
public Transform[] randomPos;
//坦克炮台看向的目标
public Transform lookAtTarget;
//开火距离
public int fireDis = 10;
//检测时间
public int fireOffsetTime = 1;
public float nowTime = 0;
//子弹与炮口
public GameObject bullet;
public Transform[] shootPos;
//关联的图片
public Texture maxHPBK;
public Texture hpBK;
//图片的坐标
private Rect maxHPRect;
private Rect hpRect;
//显示血条计时时间
private float showTime;
void Start()
{
RandomPos();
}
// Update is called once per frame
void Update()
{
#region 让坦克在两点之间不停移动
//控制坦克的移动
transform.LookAt(targetPos);
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
//检测坐标距离
if (Vector3.Distance(transform.position, targetPos.position) < 0.5f)
{
RandomPos();
}
#endregion
#region 坦克要一直盯着玩家
if (lookAtTarget != null)
{
transform.LookAt(lookAtTarget);
//当与玩家的距离小于开火距离时,进行攻击
if(Vector3.Distance(transform.position,lookAtTarget.position) < fireDis)
{
nowTime += Time.deltaTime;
if (nowTime >= fireOffsetTime)
{
Fire();
nowTime = 0;
}
}
}
#endregion
}
public void RandomPos()
{
if (randomPos.Length <= 0)
return;
targetPos = randomPos[Random.Range(0, randomPos.Length)];
}
public override void Fire()
{
//有多少个炮口就创建多少个子弹
for (int i = 0; i < shootPos.Length; i++)
{
GameObject obj = Instantiate(bullet, shootPos[i].transform.position, shootPos[i].transform.rotation);
//控制子弹做什么
BulletObj bulletObj = obj.GetComponent<BulletObj>();
bulletObj.SetFather(this);
}
}
public override void Dead()
{
base.Dead();
//增加分数
GamePanel.Instance.AddScore(10);
}
private void OnGUI()
{
if (showTime > 0)
{
showTime -= Time.deltaTime;
//设置坐标
Vector3 screenPos = UnityEngine.Camera.main.WorldToScreenPoint(transform.position);
screenPos.y = Screen.height - screenPos.y;
//绘制底图
maxHPRect.x = screenPos.x - 50;
maxHPRect.y = screenPos.y - 50;
maxHPRect.width = 100;
maxHPRect.height = 15;
GUI.DrawTexture(maxHPRect, maxHPBK);
//绘制血条
hpRect.x = screenPos.x - 50;
hpRect.y = screenPos.y - 50;
hpRect.width = (float)hp / maxHP * 100f;
hpRect.height = 15;
GUI.DrawTexture(hpRect, hpBK);
}
}
public override void Wound(TankBaseObj other)
{
base.Wound(other);
showTime = 3;
}
}