위와 같이 총알을 오브젝트 풀에서 생성해준 후
위치를 설정해주었다.
총알 생성 -> OnEnable -> 위치 할당 -> Start
순서로 코드가 실행되어
아래와 같이 코드를 짜 해결하였다.
Bullet.cs
using System;
using UnityEngine;
public class Bullet : PoolObject
{
public event Action OnHitBullet;
[SerializeField] private float bulletSpeed;
[SerializeField] private float bulletLifeTime;
private Vector3 startPos;
private Vector3 targetPos;
private Vector3 bulletDir;
private Rigidbody rigidbody;
private float lifeTimer;
private bool isShot = false;
private void Awake()
{
rigidbody = GetComponent<Rigidbody>();
}
private void OnEnable()
{
Init();
}
private void Update()
{
if (!isShot)
{
Shoot();
isShot = true;
}
lifeTimer -= Time.deltaTime;
if(lifeTimer <= 0)
{
gameObject.SetActive(false);
OnHitBullet = null;
}
}
void Init()
{
bulletDir = Vector3.zero;
// bulletLifeTime 초기화
lifeTimer = bulletLifeTime;
// 이전 총알 속도 제거
rigidbody.velocity = Vector3.zero;
isShot = false;
}
void Shoot()
{
// 위치 세팅
startPos = transform.position;
targetPos = GameManager.Instance.Player.transform.position + Vector3.up * 20;
bulletDir = GetBulletDirection();
// 발사
rigidbody.AddForce(bulletDir * bulletSpeed, ForceMode.Impulse);
}
Vector3 GetBulletDirection()
{
return (targetPos - startPos).normalized;
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.layer == 7)
{
gameObject.SetActive(false);
OnHitBullet?.Invoke();
OnHitBullet = null;
}
}
}
EnemyAttackState.cs 일부
void RangedAttack()
{
if (nomalizedTime < 0.95f && nomalizedTime > stateMachine.Data.BaseAtkTransitionTime)
{
if (!alreadyAppliedDealing)
{
alreadyAppliedDealing = true;
Shoot();
}
}
else alreadyAppliedDealing = false;
}
void Shoot()
{
RangedEnemy rangedEnemy = enemy as RangedEnemy;
// 총알 생성
Bullet bullet = GameManager.Instance.Pool.SpawnFromPool(EPoolObjectType.EnemyBullet).ReturnMyComponent<Bullet>();
bullet.transform.position = rangedEnemy.bulletSpawnPos.position;
bullet.OnHitBullet += AttackTarget;
}
'게임 개발' 카테고리의 다른 글
[Unity] 보스 키우기 (6) - 완성 (0) | 2024.06.26 |
---|---|
[Unity] 보스 키우기 (5) - 버프 몬스터 (0) | 2024.06.25 |
[Unity] 보스 키우기 (3) - 코루틴 최적화 (0) | 2024.06.21 |
[Unity] 보스 키우기 게임 (2) - FSM (0) | 2024.06.20 |
[Unity] 보스 키우기 게임 (1) - 기획 (0) | 2024.06.19 |