标签:== his tac inpu position onenter cti image 清零
敌人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学院有免费课程可以参考,不懂可以参考视频!
标签:== his tac inpu position onenter cti image 清零
原文地址:https://www.cnblogs.com/dingsiki/p/9991867.html