首页 > 编程语言 > 详细

Unity 3D做2D坦克大战--敌人自动攻击AI编写

时间:2018-11-20 22:13:32      阅读:323      评论:0      收藏:0      [点我收藏+]

敌人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<SpriteRenderer>();
}
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 3D做2D坦克大战--敌人自动攻击AI编写

原文:https://www.cnblogs.com/dingsiki/p/9991867.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!