unity 不使用碰撞來得到物體

看了網上大多都是用射線和碰撞檢測來獲得物體,今天就寫一篇不用碰撞檢測獲得物體,原理是獲取物體屏幕座標和鼠標屏幕座標

先更新初始版本

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

public class CameraT : MonoBehaviour
{
    //物體下面的所有子物體
    public GameObject ObjectPa;

    //相機
    public Camera Camera;

    //存儲物體座標集合
    private List<Vector3> toScreenPoin = new List<Vector3>();

    //根據物體座標獲取物體
    private Dictionary<Vector3, GameObject> lookGo = new Dictionary<Vector3, GameObject>();
    
    void Start()
    {
        //獲取物體所有子物體座標
        foreach (var item in ObjectPa.GetComponentsInChildren<Transform>())
        {
            if (!lookGo.ContainsKey(Camera.WorldToScreenPoint(item.localPosition)))
            {
                lookGo.Add(Camera.WorldToScreenPoint(item.localPosition), item.gameObject);
            }
            toScreenPoin.Add(Camera.WorldToScreenPoint(item.localPosition));
        }
    }

    // Update is called once per frame
    void Update()
    {
        //右鍵
        if (Input.GetMouseButtonDown(0))
        {
            float dis=0;

            //得到選中的物體
            Vector3 vectorGO = Vector3.zero;
            Vector3 mousePosition= Input.mousePosition;
            for (int i = 0; i < toScreenPoin.Count; i++)
            {                
                if (i>=1)
                {
                    //判斷距離
                    float disT= Vector3.Distance(toScreenPoin[i], mousePosition);
                    if (dis > disT)
                    {
                        dis = disT;
                        vectorGO = toScreenPoin[i];
                        //Debug.Log(dis + ":" + toScreenPoin[i] + ":" + mousePosition);
                        //Debug.Log("名字" + lookGo[toScreenPoin[i]].name);
                    }
                }
                else
                {
                    dis = Vector3.Distance(toScreenPoin[i], mousePosition);
                }
            }
            Debug.Log(dis+":"+ vectorGO);
            Debug.Log("選中物體名字" + lookGo[vectorGO].name);

        }
    }
}

後續繼續更

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章