와와

[ Unity 슈팅게임 ] 3. 마우스 클릭으로 총알 발사 본문

개발/Unity 3D

[ Unity 슈팅게임 ] 3. 마우스 클릭으로 총알 발사

정으주 2022. 8. 20. 11:17

 

 

 

< Bullet.cs >

: 총알 오브젝트 (프리펩)

 

- 생성된 총알은 직선으로 쭉 나아감

- 총알 오브젝트가 화면 밖( y축으로 1000 이상 )을 벗어나면 삭제

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float bulletSpeed = 15f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Vector3.up * Time.deltaTime * bulletSpeed);

        Vector3 view = Camera.main.WorldToScreenPoint(transform.position);
        if (view.y > 1000)
        {
            Destroy(gameObject); 
        }      
    }
}

 

 

 

 

< Fire.cs >

: 플레이어 오브젝트

 

- 마우스 클릭하면 플레이어 위치에서 총알 생성

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Fire : MonoBehaviour
{
    public GameObject BulletFactory;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if ( Input.GetMouseButtonDown(0))
        {
            Instantiate(BulletFactory, transform.position, transform.rotation);
        }
    }
}