簡體   English   中英

旋轉的 object 的 x 軸和 z 軸倒轉為單位 3d

[英]Rotated object has x and z axis inversed in unity 3d

我正在 Unity 中制作游戲,它是一個 3d 項目。 在我將一個 object 拖到另一個 object 旁邊並且距離不太大之后,我希望它們合並。 如果我將 object 放在另一個的右側,我希望它在右側合並,如果我放在左側則反轉。

If the objects are rotated, Z axis position will change with the X axis position and I won't know what position should I add to the dragged object so they will be merged together.

有人可以幫我寫一個代碼嗎?

我知道你想要什么。 我認為您的意思是兩個球互相撞擊,並且您希望它們一起移動。 我的第一個想法是,您可以設置擊中它的 object 和擊中它的 object 的孩子可以移動的空游戲 object。 應該使用OnTriggerEnter(Collider other)OnCollisionEnter(Collision other) 我將在下面的示例中使用一個,稍后我將向您展示如何更改它們。

using UnityEngine;

//Important: only attach script to one of the objects you want to group.
public class exampleClass : MonoBehaviour
{
   public GameObject empty;
   void OnTriggerEnter(Collider other)
   {
      if (other.gameObject.tag == “exampleTag”)
    //change tag to the tag of the object(s) you want to join.
      {
         Join(other.gameObject);
      }
   }
   void Join(GameObject obj)
   {
      var parent = Instantiate(empty, transform.position);
      transform.parent = parent.transform;
      obj.transform.parent = parent.transform;
   }
}

這是一個基本腳本,它將對象加入一個組,其中父對象(控制其他兩個對象的對象)可以同時移動/旋轉兩者。 如果您想讓他們使用OnCollisionEnter() (答案底部的鏈接了解何時使用觸發器或碰撞),那么您將OnTriggerEnter(Collider other)更改為OnCollisionEnter(Collision other) 現在,父 object 位於上面有腳本的 object 的中心。 我們可以使用插值將其更改為兩個碰撞對象的中間。 插值基於 0 - 1 的值在兩個向量或浮點數之間獲取一個點。將Join(GameObject obj)方法的一部分更改為:

...
   void Join(GameObject obj)
   {
      Vector3 middle = Vector3.Lerp(transform.position, obj.transform.position, 0.5f);
      var parent = Instantiate(empty, middle);
      transform.parent = parent.transform;
      obj.transform.parent = parent.transform;
   }

它找到對象的 position 和命中對象的 position 的中間。 (您可以將 0.5f 更改為 0.1f 為對象的 position 到被擊對象的 position 的十分之一。)

您可能只是想看看它們是否有一定的距離,然后執行代碼的 rest。 如果這樣做,那么您將需要更改以下代碼:


using UnityEngine;

//Important: only attach script to one of the objects you want to group.
public class exampleClass : MonoBehaviour
{
   public float maxDist = 1f;
   public GameObject empty;
   void Update()
   {
      GameObject[] objects = FindGameObjectsWithTag(“exampleTag”);
    //change tag to the tag of the object(s) you want to join.
      for (int i = 0; i < objects.Length; i++)
      {
         float distance = Vector3.Distance(objects[i].transform.position, transform.position);
         if (distance <= maxDist)
         {
            Join(other.gameObject);
         }
      }
   }
...

此代碼使用Vector3.Distance()查找任何帶有某個標簽的 object 與帶有腳本的 object 之間的距離。 如果該距離小於或等於要加入的最大距離,則它會加入對象。 如果您遇到任何錯誤或這與您的預期不符,請在此帖子上發表評論。

一些額外幫助的鏈接:

實例化

OnCollisionEnter()OnTriggerEnter()

矢量3.距離

插值:

什么是插值

矢量3

浮動

暫無
暫無

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

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