간단한 유도 미사일 구현하기!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MissileLauncher : MonoBehaviour
{
[SerializeField]
GameObject m_goMissile = null;
[SerializeField]
Transform m_tfMissileSpawn = null;
private void Start()
{
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha3))
{
GameObject t_missile = Instantiate(m_goMissile, m_tfMissileSpawn.position, Quaternion.identity);
t_missile.GetComponent<Rigidbody>().velocity = Vector3.up * 5f;
}
}
}
이건 이제 발사를 시켜주기 위한 코드 입니다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Missile : MonoBehaviour
{
private const string playerTag = "Player";
public GameObject sparkEffect;
Rigidbody m_rigid = null;
Transform m_tfTarget = null;
[SerializeField]
float m_speed = 0f;
float m_currentSpeed = 0f;
[SerializeField]
LayerMask m_layerMask = 0;
[SerializeField]
ParticleSystem m_psEffect = null;
void SearchEnemy()
{
Collider[] t_cols = Physics.OverlapSphere(transform.position, 100f, m_layerMask);
if(t_cols.Length > 0)
{
m_tfTarget = t_cols[Random.Range(0, t_cols.Length)].transform;
}
}
IEnumerator LaunchDelay()
{
yield return new WaitUntil(() => m_rigid.velocity.y < 0f);
yield return new WaitForSeconds(0.1f);
SearchEnemy();
m_psEffect.Play();
yield return new WaitForSeconds(5f);
Destroy(gameObject);
}
private void Start()
{
m_rigid = GetComponent<Rigidbody>();
StartCoroutine(LaunchDelay());
}
private void Update()
{
if(m_tfTarget != null)
{
if (m_currentSpeed <= m_speed)
m_currentSpeed += m_speed * Time.deltaTime;
transform.position += transform.up * m_currentSpeed * Time.deltaTime;
Vector3 t_dir = (m_tfTarget.position - transform.position).normalized;
transform.up = Vector3.Lerp(transform.up, t_dir, 0.25f);
}
}
void ShowEffect(Collision coll)
{
// 충돌 지점의 정보를 추출
ContactPoint contact = coll.contacts[0];
// 법선 벡터가 이루는 회전각도를 추출
Quaternion rot = Quaternion.FromToRotation(-Vector3.forward, contact.normal);
// 폭발 효과 프리팹을 동적으로 생성
/*
* Instantiate 함수의 3번째 인자는 회전각도로서 Quaternion 타입니다.
* Quaternion.identity 의 의미는 프리팹을 무회전 또는 회전값이 없는 상태로 적용한다
*/
GameObject effect = Instantiate(sparkEffect, this.transform.position, Quaternion.identity);
GameObject effect = Instantiate(sparkEffect, contact.point, rot);
Destroy(effect, 2.0f);
PoolManager.Instance.Despawn(effect, 2f);
}
private void OnCollisionEnter(Collision coll)
{
if (coll.transform.CompareTag("ENEMY"))
{
Destroy(coll.gameObject);
}
if (coll.transform.tag != playerTag)
{
Destroy(this.gameObject);
}
}
}
이 코드가 바로 유도 미사일 코드 입니다 ENEMY 라는 태그가 걸린 오브젝트 들을 찾아 다니게 되는거죠