사전캠프/TIL
2025-01-02 TIL
danpat77
2025. 1. 2. 20:42
저번에 캐릭터 움직이는 것을 만들었으니 오늘은 총쏘는 기능을 추가해 줄 것이다.
우선 캐릭터에 어울리는 애니메이션과 총을 넣어주고
총알이 발사될 위치에 Create Empty를 만들어 aim이라고 이름이 지어준다.
Aim.cs를 만들어
public class Aim : MonoBehaviour
{
public static Aim Instance;
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
public int restBullet = 30;
public int maxBullet = 30;
bool isShooting = false;
bool isReroding = false;
public GameObject aim;
public GameObject bullet;
private void Start()
{
restBullet = maxBullet;
}
private void Update()
{
if (Input.GetMouseButton(0) && restBullet > 0 && !isShooting && isReroding == false)
{
StartCoroutine(Shooting());
}
if (Input.GetKey(KeyCode.R))
{
StartCoroutine(reRoding());
Debug.Log("Reroding");
}
showText();
}
IEnumerator Shooting()
{
isShooting = true;
while (Input.GetMouseButton(0) && restBullet > 0)
{
Instantiate(bullet, aim.transform.position, Quaternion.identity);
restBullet--;
Debug.Log(restBullet);
yield return new WaitForSeconds(0.08f);
}
isShooting = false;
}
IEnumerator reRoding()
{
isReroding=true;
yield return new WaitForSeconds(1.5f);
restBullet = maxBullet;
Debug.Log(restBullet);
isReroding = false;
}
}
총알 생성은 코루틴을 사용해서 마우스 좌클릭을 하면 Shooting()이 작동하게 해준다.
Shooting()에는 bool값을 이용해 마우스 좌클릭을 누르고 있을때 true 땔때 false가 되게 해주어 마우스에 손을때도 총알이 발사가 되는 상황을 막아준다. 그리고 총알수도 정해줘서 한 탄창 내 총알 수도 제한해 준다.
다음으로 총알도 적당히 만들어주고 Rigidbody와 Bullet.cs를 추가해 준 후 Prefab으로 만들어 준다.
public class Bullet : MonoBehaviour
{
public GameObject aim;
private void Start()
{
aim = Aim.Instance.aim;
transform.forward = aim.transform.forward;
}
private void Update()
{
transform.position += transform.forward * 0.05f;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Map"))
{
Destroy(this.gameObject);
}
if (other.gameObject.CompareTag("Enum"))
{
Destroy(this.gameObject);
}
}
}
총알이 정면을 향해 날라갈수 있게 aim.cs에서 총구 위치를 지정해준 GameObject를 가져와 Start() 함수를 이용해서 Bullet.cs가 작동을 하면 총구의 앞 뱡향과 총알의 앞 방향을 같게 만들어준다.
Aim.cs에서 총알을 생성을 하면 Prefab해준 총알이 생겨 계속 앞으로 갈 수있게 해주고 tag가 Map이거나 Enum을 가지고 있으면 충돌후 사라지게 만들어준다.