74 lines
2.8 KiB
C#
74 lines
2.8 KiB
C#
using UnityEngine;
|
||
using RR.Game2D.Entities.Projectiles;
|
||
using RR.Game2D.Behaviour.ScriptableObjects;
|
||
using RR.Game2D.Core.Managers;
|
||
|
||
namespace RR.Game2D.Behaviour
|
||
{
|
||
public class EnemyFireScript : MonoBehaviour
|
||
{
|
||
[SerializeField] private EnemyFireConfiguration config;
|
||
|
||
private float lastThrowTime = -999f;
|
||
private EnemyBasicProjectile _projectile;
|
||
|
||
void Start()
|
||
{
|
||
lastThrowTime = Time.time;
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
if (!config.projectilePrefab)
|
||
{
|
||
Debug.LogError("EnemyFireScript: projectile prefab missing; assign projectile prefab in the inspector");
|
||
return;
|
||
}
|
||
|
||
//if (projectile != null && Time.time - lastThrowTime >= projectile.maxLifetime)
|
||
// projectile.Despawn();
|
||
|
||
// Бросок
|
||
if (Time.time - lastThrowTime >= config.throwCooldown)
|
||
Throw();
|
||
}
|
||
|
||
private void OnDestroy()
|
||
{
|
||
// При смерти врага сго снаряд тоже пропадает
|
||
if (_projectile != null) _projectile.Despawn();
|
||
}
|
||
|
||
/// <summary>
|
||
/// Метод для броска снаряда (выстрела).
|
||
/// У снаряда обязательно должен быть метод Launch(Vector2 direction)
|
||
/// </summary>
|
||
private void Throw()
|
||
{
|
||
float rotationY = transform.localEulerAngles.y;
|
||
Vector2 throwDirection = rotationY >= 180f ? Vector2.right : Vector2.left;
|
||
Collider2D enemyCol = GetComponent<Collider2D>();
|
||
Vector2 throwPosition = new(1.4f * throwDirection.x + transform.position.x, enemyCol.bounds.center.y);
|
||
|
||
_projectile = Instantiate(config.projectilePrefab, throwPosition, Quaternion.identity);
|
||
_projectile.owner = gameObject;
|
||
_projectile.maxLifetime = config.projectileLifetime;
|
||
_projectile.despawnInstantly = config.projectileDespawnInstantly;
|
||
_projectile.fallGravityScale = config.projectileFallGravityScale;
|
||
|
||
Collider2D projectileCol = _projectile.GetComponent<Collider2D>();
|
||
|
||
_projectile.transform.localRotation = throwDirection.x < 0 ? Quaternion.Inverse(_projectile.transform.localRotation) : _projectile.transform.localRotation;
|
||
|
||
_projectile.transform.position = throwPosition;
|
||
_projectile.Launch(throwDirection, config.throwSpeed);
|
||
|
||
if (config.shotSounds.Length > 0)
|
||
GameManager.Instance.Audio.PlayRandomSfxAt(config.shotSounds, throwPosition);
|
||
|
||
if (enemyCol && projectileCol) Physics2D.IgnoreCollision(enemyCol, projectileCol, true);
|
||
|
||
lastThrowTime = Time.time;
|
||
}
|
||
}
|
||
} |