unity自动生成敌人_Unity 3D做2D坦克大战--敌人自动攻击AI编写
敵人AI攻擊方法的編寫
老師 | Trigger
學習者 |小白
出品 | Siki 學院
```java
public class Enemy : MonoBehaviour
{
//屬性值
public float movespeed = 3;
private Vector3 bullectEulerAngles;
private float v = -1;
private float h;
//引用
private SpriteRenderer sr;
public Sprite[] tanksprite;// 上 右 下 左
public GameObject bullectPrafabs;
public GameObject explosionPrefab;
//計時器
private float timeVal;
private float timeValChangeDirection;//改變方向的計時器
private void Awake()
{
sr = GetComponent();
}
void Update()
{
//攻擊的時間間隔
if (timeVal >= 3f)
{
Attack();
}
else
{
timeVal += Time.deltaTime;
}
}
private void FixedUpdate()
{
Move();
}
private void Attack()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(bullectPrafabs, transform.position, Quaternion.Euler(transform.eulerAngles + bullectEulerAngles));
timeVal = 0;
}
}
//坦克的移動方法
private void Move()
{
if (timeValChangeDirection >= 4)//如果攻擊后4秒產生轉向
{
int num = Random.Range(0, 8);
if (num > 5)//向下走
{
v = -1;
h = 0;
}
else if (num == 0)//往回走
{
v = 1;
h = 0;
}
else if (num > 0 && num <= 2)//向左走
{
h = -1;
v = 0;
}
else if (num > 2 && num <= 4)//向右走
{
h = 1;
v = 0;
}
timeValChangeDirection = 0; //計時器清零
}
else
{
timeValChangeDirection += Time.fixedDeltaTime; //計時器累加
}
transform.Translate(Vector3.up *this.v* movespeed * Time.fixedDeltaTime, Space.World);
if (v < 0)
{
sr.sprite = tanksprite[2];
bullectEulerAngles = new Vector3(0, 0, -180);
}
else if (v > 0)
{
sr.sprite = tanksprite[0];
bullectEulerAngles = new Vector3(0, 0, 0);
}
transform.Translate(Vector3.up * v * movespeed * Time.fixedDeltaTime, Space.World);
if (v != 0)
{
return;
}
transform.Translate(Vector3.right * h * movespeed * Time.fixedDeltaTime, Space.World);
if (h < 0)
{
sr.sprite = tanksprite[3];
bullectEulerAngles = new Vector3(0, 0, 90);
}
else if (h > 0)
{
sr.sprite = tanksprite[1];
bullectEulerAngles = new Vector3(0, 0, -90);
}
}
private void Die()
{
//爆炸特效
Instantiate(explosionPrefab, transform.position, transform.rotation);
//死亡方法
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
timeValChangeDirection = 4;
}
}
}
```
SiKi學院有免費課程可以參考,不懂可以參考視頻!
總結
以上是生活随笔為你收集整理的unity自动生成敌人_Unity 3D做2D坦克大战--敌人自动攻击AI编写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue实现进度条隐藏_实现带有进度条的V
- 下一篇: AI 趋势