K-digital traning/유니티 심화

OverlapSphere 연습

내꺼블로그 2023. 8. 21. 18:20

1.구현한 내용

- Sphere범위 내 가장 가까운 무기 장착하기

 

 

 

2.code

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

public class OverlapPlayer : MonoBehaviour
{
    [SerializeField]
    private float radius = 1f;
    private Collider[] colls = new Collider[6];

    [SerializeField]
    private Transform trans;

    private void Start()
    {
        int layerMask = 1 << LayerMask.NameToLayer("Gun");
        int cnt = Physics.OverlapSphereNonAlloc(this.transform.position, radius, colls, layerMask);
        Debug.Log(cnt);
        float minDis = 10000f;
        GameObject gunGo = null;
        foreach(var coll in colls)
        {
            Debug.Log(coll.gameObject.name);
            float dis = Vector3.Distance(coll.transform.position, this.transform.position);
            Debug.Log(dis);
            if (dis < minDis)
            {
                gunGo = coll.gameObject;
                minDis = dis;
            }
        }
        gunGo.transform.SetParent(this.trans);
        gunGo.transform.localPosition = Vector3.zero;
        gunGo.transform.localRotation=Quaternion.identity;
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

 

 

3.결과