簡體   English   中英

c# - 如何在c#中使用unity組合網格並獲取相對於主父級的單擊位置

[英]how to combine meshes and get click location with respect to main parent in c# using unity

假設我在 Unity 中有一個 3D 塔。 塔的結構使得 Transform 父級有子級,其中每個子級代表塔的一層。 孩子本身是一個空的游戲對象(只有組件是一個變換),並且它們是許多(自定義)網格的父級(每個孫子都是一個單獨的自定義網格)。 我如何組合這些網格,以便我可以點擊塔樓地板上的某個地方,然后獲得該點擊相對於塔樓作為塔樓整體/局部位置的坐標?

我會在根上有一個專門的類

public class Tower : MonoBehaviour { }

那么你可以在所有孩子MeshCollider都有一個MeshCollider (或任何Collider但當然你會得到碰撞器上的位置而不是顯示的網格)並且做

// Get a ray of your click position
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// Shoot a raycast
if(Physics.Raycast(ray, out var hit))
{
    // Try to get the Tower component of the parent
    // bubbles up until it finds according component or returns null
    var tower = hit.gameObject.GetComponentInParent<Tower>();
    // Are we clicking at any child under a Tower component?
    if(tower)
    {
        // get the hit point in world space
        var worldPoint = hit.point;
        // Get the hit point relative to the tower's pivot
        var relativePoint = tower.transform.InverseTransformPoint(worldPoint);

        Debug.Log($"You have hit tower at {relativePoint.ToString("G9")}");     
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM