공부/Unity
[Unity] 1인칭 FPS 총알 발사하기
돌멩이수프
2022. 5. 17. 13:12
728x90
내가 원하는 모습 : 마우스 좌클릭 시 prefab 상에 있는 총알이 Player의 총구 위치에서 생성되어 앞으로 발사됨
https://blog.naver.com/ghost365/221380308534 참고
1. 총알이 생성될 위치를 FirePos로 지정
2. flaregun에 마우스 좌클릭 시 일어날 이벤트 조정
public class GunShot : MonoBehaviour
{
public GameObject bulletFactory;
public Transform FirePos;
private void Update()
{
if (Input.GetMouseButtonDown(0))
Shoot();
}
void Shoot()
{
GameObject _bullet = Instantiate(bulletFactory);
_bullet.transform.position = FirePos.position;
}
}
3. 총알 prefab에 script 추가
public class Crush : MonoBehaviour
{
void Update()
{
Transform _camera = GameObject.Find("Main Camera").transform;
transform.Translate(_camera.GetComponent<Transform>().forward * 0.2f, Space.World);
}
}
플레이어에서 위치를 가져오면 총알의 x rotation에 아무런 변화가 없어서 카메라 기준 rotation을 가져왔다.
4. GunShot에 bulletFactory, FirePos 지정
총알이 잘 나간다!
728x90