유니티 심화

OverlapSphere[수정필]

다모아 2023. 8. 21. 18:15

OverlapPlayer

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

public class OverlapPlayer : MonoBehaviour
{
    [SerializeField]
    private float radius = 1f;
    [SerializeField]
    private Transform weaponTr;

    private Collider[] colls = new Collider[6];
    private float distance = 0f;
    private Collider coll;
    private void Start()
    {
        int layerMask = 1 << LayerMask.NameToLayer("Gun"); ;
        int cnt = Physics.OverlapSphereNonAlloc(this.transform.position, this.radius, colls, layerMask);
        Debug.Log(cnt);

        int i = 0;
        foreach (Collider col in colls)
        {
            float distance = Vector3.Distance(this.transform.position, this.colls[i++].transform.position);
            if(distance >= 0)
            {
                this.distance = distance;
                this.coll = col;
            }
            else if(this.distance <= distance)
            {
                this.distance = distance;
                this.coll = col;
            }
        }
        Debug.Log(this.distance);
        Debug.Log(this.coll.gameObject.name);

        this.coll.gameObject.transform.SetParent(this.weaponTr);
        this.coll.gameObject.transform.position = this.weaponTr.transform.position;
        this.coll.gameObject.transform.rotation = Quaternion.identity;
    }
    private void OnDrawGizmos()
    {
        int idx = 0;
        Gizmos.DrawWireSphere(this.transform.position, this.radius);
    }
}

가까운거가 아님..