为我们的新敌人准备图片精灵Sprite。
我们的敌人拥有两个涡轮增压器。
private enum EnemyType
{
Default,
Zigzag,
Aggressive,
Smart
}
我们的水平激光器及其所有组件。
[SerializeField] private bool _isHorizontalLaser = false;
private int _direction = 1;
private void CalculateMovement()
{
if (_isPlayerLaser)
transform.Translate(_laserSpeed * Time.deltaTime * Vector3.up);
else
{
if (!_isHorizontalLaser)
transform.Translate(_laserSpeed * Time.deltaTime * Vector3.down);
else
{
Vector3 horizontalDirection = Vector3.right * _direction;
transform.Translate(_laserSpeed * Time.deltaTime * horizontalDirection);
}
}
}
public void SetDirection(int direction)
{
_direction = direction;
}
private void FireLaser()
{
if(_type == EnemyType.Aggressive)
_fireRate = Random.Range(1.5f, 3f);
else
_fireRate = Random.Range(3f, 7f);
_canFire = Time.time + _fireRate;
if (_type != EnemyType.Smart)
{
_laserOffset.Set(0f, -1.4f, 0f);
Instantiate(_laserPrefab, transform.position + _laserOffset, Quaternion.identity);
}
else
{
if(_direction > 0)
_laserOffset.Set(1.35f, 0f, 0f);
else
_laserOffset.Set(-1.35f, 0f, 0f);
GameObject laserObj = Instantiate(_laserPrefab, transform.position + _laserOffset, Quaternion.identity);
LaserBehaviour laser = laserObj.GetComponent<LaserBehavior>();
if (laser != null)
laser.SetDirection(_direction);
}
}
private void RotateEnemy()
{
if(_type == EnemyType.Smart)
{
if (_direction > 0)
{
_direction = 1;
_spriteTransform.rotation = Quaternion.Euler(0f, 180f, 0f);
}
else
{
_direction = -1;
_spriteTransform.rotation = Quaternion.Euler(0f, 0f, 0f);
}
}
}
private void Update()
{
CalculateMovement();
if (Time.time >= _canFire && _type != EnemyType.Zigzag)
{
if (_type != EnemyType.Smart)
FireLaser();
else
{
Vector2 toPlayer = _player.transform.position - transform.position;
float angle = Vector2.SignedAngle(-transform.right, toPlayer.normalized);
float alignmentThreshold = 5f;
float horizontalAlignment = Mathf.Abs(toPlayer.y) / Mathf.Abs(toPlayer.x);
if (Mathf.Abs(angle) < alignmentThreshold && horizontalAlignment < 1f)
FireLaser();
}
}
}
我们可以看到,只有当玩家在他身后并与他对齐时,敌人才会开枪。