61 lines
1.9 KiB
C#
61 lines
1.9 KiB
C#
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
|
|
public class EnemyFireScript : MonoBehaviour
|
|
{
|
|
[Header("Снаряд")]
|
|
[SerializeField] private BasicProjectile projectilePrefab;
|
|
[SerializeField] private float projectileLifetime = 1f;
|
|
[SerializeField] private float throwCooldown = 5f;
|
|
[SerializeField] private float throwSpeed = 20f;
|
|
|
|
private float lastThrowTime = -999f;
|
|
private BasicProjectile projectile;
|
|
|
|
//private BasicProjectile projectile;
|
|
|
|
void Start()
|
|
{
|
|
lastThrowTime = Time.time;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (!projectilePrefab)
|
|
{
|
|
Debug.LogError("EnemyFireScript: projectile prefab missing; assign projectile prefab in the inspector");
|
|
return;
|
|
}
|
|
|
|
if (Time.time - lastThrowTime >= throwCooldown)
|
|
{
|
|
Throw();
|
|
lastThrowTime = Time.time;
|
|
}
|
|
|
|
if (projectile != null && Time.time - lastThrowTime >= projectile.maxLifetime)
|
|
projectile.Despawn();
|
|
}
|
|
|
|
|
|
private void Throw()
|
|
{
|
|
float rotationX = transform.localRotation.x;
|
|
Vector2 throwDirection = rotationX >= 180 ? 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.maxLifetime = projectileLifetime;
|
|
|
|
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);
|
|
}
|
|
}
|