Unity/공부한 내용

유니티 3D 일정 범위 안에 있는 오브젝트 찾기, 가장 가까운 오브젝트 찾기

선글냥 2023. 2. 15. 00:37
유니티 3D 일정 범위 안에 있는 오브젝트 찾기

 

검출 될 콜라이더 레이어를 Enemy로 바꾼후 스크립트에서 Enemy만 검출되게 바꾼다

 

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

public class overlapsphere : MonoBehaviour
{
    public float radius = 0f;
    public LayerMask layer;
    public Collider[] colliders;

    void Start()
    {
        
    }

    void Update()
    {
        colliders = Physics.OverlapSphere(transform.position, radius, layer);
    }
   
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

 

유니티 3D 일정 범위 안에 있는 오브젝트 찾기

 

 

 

 

 

유니티 3D 일정 범위 안에 있는 가장 가까운 오브젝트 찾기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class overlapsphere : MonoBehaviour
{
    public float radius = 0f;
    public LayerMask layer;
    public Collider[] colliders;
    public Collider short_enemy;
    

    void Start()
    {
        
    }

    void Update()
    {
        colliders = Physics.OverlapSphere(transform.position, radius, layer);

        if(colliders.Length > 0)
        {
            float short_distance = Vector3.Distance(transform.position, colliders[0].transform.position);
            foreach(Collider col in colliders)
            {
               float short_distance2 = Vector3.Distance(transform.position, col.transform.position);
               if (short_distance > short_distance2)
                {
                    short_distance = short_distance2;
                    short_enemy = col;
                }
            }

        }

    }
   
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, radius);
    }
}

유니티 3D 일정 범위 안에 있는 가장 가까운 오브젝트 찾기

 

 

 

https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

 

Unity - Scripting API: Vector3.Distance

Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close

docs.unity3d.com

 

https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html