반응형

 

Gun 오브젝트를 선택하고 총알이 나올 수 있는 포인트를 만들어 주어야 합니다 

그래서 새로운 오브젝트를 Create Empty 를 생성하고 자식으로 이름을 sPoint라고 합니다 

GunCtrl 스크립트 수정

아래와 같이 GunCtrl 스크립트를 수정합니다 

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

public class GunCtrl : MonoBehaviour
{
    public GameObject bullet;
    public Transform sPoint;
    public float timeBetweenShots;


    private float shotTime;

    void Update()
    {
        //카메라 스크린의 마우스 거리와 총과의 방향 
        Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        //마우스 거리로 부터 각도 계산
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        //축으로부터 방향과 각도의 회전값
        Quaternion rotation = Quaternion.AngleAxis(angle , Vector3.forward);
        transform.rotation = rotation;

        //마우스 왼쪽버튼을 눌렀을때
        if (Input.GetMouseButton(0))
        {
            if (Time.time >= shotTime)
            {
                //총알을 생성한다
                Instantiate(bullet, sPoint.position, Quaternion.AngleAxis(angle - 90,Vector3.forward));
                //재장전 총알 딜레이 
                shotTime = Time.time + timeBetweenShots;
            }
        }
    }
}

 

 

 

 

수정된 GunCtrl 스크립트에 프리팹으로 만들었던 bullet과 Gun 오브젝트의 자식으로 있는 sPoint를 GunCtrl스크립트에 연결합니다 

 

아래 동영상과 같이 총알이 나오는 것을 볼 수 있습니다 

 

bullet 프리팹을 선택하여 BulletCtrl 스크립트를 생성하고 작성합니다 

 

 

 

 

BulletCtrl 스크립트를 작성합니다 

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

public class BulletCtrl : MonoBehaviour
{
    public float speed;
    public float lifeTime;

    // Start is called before the first frame update
    void Start()
    {
        // 총알을 시간에 맞게 지운다 
        Destroy(gameObject, lifeTime);
    }

    // Update is called once per frame
    void Update()
    {
        // 시간프레임과 speed에 따라 y축방향으로 움직인다 
        transform.Translate(Vector2.up * speed * Time.deltaTime);
    }
}

 

 

아래 동영상과 같이 마우스에 따라 총이 움직이고 총알이 마우스에 따라 방향대로 발사되는 것을 확인합니다 

 

반응형

+ Recent posts