Danro/Assets/Scripts/Behaviour/EnemyFireScript.cs

70 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using RR.Game2D.Entities.Projectiles;
using RR.Game2D.Behaviour.ScriptableObjects;
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 (enemyCol && projectileCol) Physics2D.IgnoreCollision(enemyCol, projectileCol, true);
lastThrowTime = Time.time;
}
}
}