77 lines
2.9 KiB
C#
77 lines
2.9 KiB
C#
using UnityEngine;
|
||
using RR.Game2D.Entities.Projectiles;
|
||
|
||
namespace RR.Game2D.Behaviour
|
||
{
|
||
public class EnemyFireScript : MonoBehaviour
|
||
{
|
||
[Header("Бросок")]
|
||
[SerializeField] private float throwCooldown = 5f;
|
||
[SerializeField] private float throwSpeed = 20f;
|
||
|
||
[Header("Снаряд")]
|
||
[SerializeField] private EnemyBasicProjectile projectilePrefab;
|
||
[SerializeField] private float projectileLifetime = 1f;
|
||
[SerializeField] private bool projectileDespawnInstantly = false;
|
||
[SerializeField] private float projectileFallGravityScale = 3f;
|
||
|
||
private float lastThrowTime = -999f;
|
||
private EnemyBasicProjectile projectile;
|
||
|
||
void Start()
|
||
{
|
||
lastThrowTime = Time.time;
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
if (!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 >= 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(projectilePrefab, throwPosition, Quaternion.identity);
|
||
projectile.owner = gameObject;
|
||
projectile.maxLifetime = projectileLifetime;
|
||
projectile.despawnInstantly = projectileDespawnInstantly;
|
||
projectile.fallGravityScale = 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, throwSpeed);
|
||
|
||
if (enemyCol && projectileCol) Physics2D.IgnoreCollision(enemyCol, projectileCol, true);
|
||
|
||
lastThrowTime = Time.time;
|
||
}
|
||
}
|
||
} |