[敌人的脚本]
public class Enemy : MonoBehaviour
{
//属性值
public float moveSpeed = 3;
public Vector3 bulletEulerAngle;
private float v;
private float h;
//引用
private SpriteRenderer sr;
public Sprite[] tankSprite;
public GameObject bulletPrefab;
public GameObject explosionPrefab;
//计时器
public float timeVal;
public float timeValChangeDirection=4;
private void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
void Start()
{
}
void Update()
{
//攻击的时间间隔
if (timeVal >= 3)
{
Attack();
}
else
{
timeVal += Time.deltaTime;
}
}
private void FixedUpdate()
{
Move();
}
//坦克的攻击方法
private void Attack()
{
//子弹产生的角度:当前坦克的角度+子弹应该旋转的角度
Instantiate(bulletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngle));
timeVal = 0;
}
//坦克的移动方法
private void Move()
{
if (timeValChangeDirection >= 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;
h = 0;
}
else if (num > 2 && num <= 4)
{
h = 1;
v = 0;
}
timeValChangeDirection = 0;
}
else
{
timeValChangeDirection += Time.fixedDeltaTime;
}
transform.Translate(Vector3.up * v * Time.fixedDeltaTime * moveSpeed, Space.World);
if (v < 0)
{
sr.sprite = tankSprite[2];
bulletEulerAngle = new Vector3(0, 0, -180);
}
else if (v > 0)
{
sr.sprite = tankSprite[0];
bulletEulerAngle = new Vector3(0, 0, 0);
}
if (v != 0) return;
transform.Translate(Vector3.right * h * Time.fixedDeltaTime * moveSpeed, Space.World);
if (h < 0)
{
sr.sprite = tankSprite[3];
bulletEulerAngle = new Vector3(0, 0, 90);
}
else if (h > 0)
{
sr.sprite = tankSprite[1];
bulletEulerAngle = new Vector3(0, 0, -90);
}
}
//坦克的死亡方法
private void Die()
{
Instantiate(explosionPrefab, transform.position, transform.rotation);
Destroy(gameObject);
}
}
[Player的攻击脚本]
public float timeVal;
public GameObject bulletPrefab;
void Update()
{
if(timeVal >= 0.4f)
{
Attack();
}
else
{
timeVal += Time.deltaTime;
}
}
//坦克的攻击方法
private void Attack()
{
if (Input.GetKey(KeyCode.Space))
{
Instantiate(bulletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngle));
timeVal = 0;
}
}
[系统没有报错]