Projext/Assets/Scripts/Enemy/AI/Projectile.cs

83 lines
2.1 KiB
C#
Raw Normal View History

2026-02-04 14:06:25 +00:00
using UnityEngine;
/// <summary>
/// 원거리 공격 발사체 (화살, 마법탄 등)
/// </summary>
public class Projectile : MonoBehaviour
{
private Vector3 _direction;
private float _speed;
private float _damage;
private bool _isInitialized = false;
[Header("설정")]
[SerializeField] private float lifetime = 5f; // 수명
[SerializeField] private GameObject hitEffectPrefab; // 충돌 이펙트
private Rigidbody _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
}
/// <summary>
/// 발사체 초기화
/// </summary>
public void Initialize(Vector3 direction, float speed, float damage)
{
_direction = direction.normalized;
_speed = speed;
_damage = damage;
_isInitialized = true;
// Rigidbody로 발사
if (_rigidbody != null)
{
_rigidbody.velocity = _direction * _speed;
}
// 수명 후 파괴
Destroy(gameObject, lifetime);
}
private void FixedUpdate()
{
if (!_isInitialized) return;
// Rigidbody가 없으면 수동으로 이동
if (_rigidbody == null)
{
transform.position += _direction * _speed * Time.fixedDeltaTime;
}
}
private void OnTriggerEnter(Collider other)
{
// 발사한 몬스터 무시
if (other.CompareTag("Enemy")) return;
// 플레이어와 충돌
if (other.CompareTag("Player"))
{
if (other.TryGetComponent<PlayerHealth>(out var playerHealth))
{
if (!playerHealth.isInvincible)
{
playerHealth.TakeDamage(_damage);
Debug.Log($"[Projectile] 플레이어 적중! 데미지: {_damage}");
}
}
}
// 충돌 이펙트
if (hitEffectPrefab != null)
{
Instantiate(hitEffectPrefab, transform.position, Quaternion.identity);
}
// 발사체 파괴
Destroy(gameObject);
}
}