繁体   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