유니티 C# 원하는 위치로 물건 던지기 간단 구현 방법

반응형

코드 작성

using UnityEngine;

public class ThrowObject : MonoBehaviour
{
    // 던질 객체의 프리팹을 인스펙터에서 할당합니다.
    public GameObject objectToThrow; 

    // 목표 위치의 Transform을 인스펙터에서 할당합니다.
    public Transform target; 

    // 던지는 힘을 조절할 수 있습니다.
    public float throwForce = 10f; 

    void Update()
    {
        // 마우스 왼쪽 버튼이 눌렸는지 확인하여 던지기 동작을 트리거합니다.
        if (Input.GetButtonDown("Fire1")) 
        {
            Throw();
        }
    }

    void Throw()
    {
        // 던질 객체와 목표가 할당되었는지 확인합니다.
        if (objectToThrow != null && target != null)
        {
            // 캐릭터의 위치에 던질 객체를 인스턴스화합니다.
            GameObject thrownObject = Instantiate(objectToThrow, transform.position, Quaternion.identity);

            // 목표까지의 방향을 계산합니다.
            Vector3 directionToTarget = (target.position - transform.position).normalized;

            // 던진 객체에 힘을 가합니다.
            Rigidbody rb = thrownObject.GetComponent<Rigidbody>();
            if (rb != null)
            {
                rb.AddForce(directionToTarget * throwForce, ForceMode.Impulse);
            }
        }
    }
}
반응형