如何在 Unity 的运行时中捕捉两个对象?



这是 3D 模型 我想将另一个这样的模型连接到顶部的银色连接器,并将另一个模型连接到右侧(所以请帮我捕捉它(我想知道如何在运行时将两个 3D 对象捕捉在一起。 即在"播放"期间,用户必须能够拖动, 向下,向左,向右将一个对象与另一个对象对齐,例如"乐高",即。一个 3D 对象应捕捉到另一个 3D 对象。我将如何实现这一目标?

这是我用于拖动的代码:

using System.Collections;
using UnityEngine;
public class drag : MonoBehaviour {
Vector3 dist;
float posX;
float PosY;
void OnMouseDown()
{
dist = Camera.main.WorldToScreenPoint(transform.position);
posX = Input.mousePosition.x - dist.x;
PosY = Input.mousePosition.y - dist.y;
}
void OnMouseDrag()
{
Vector3 curPos = new Vector3(Input.mousePosition.x - posX, Input.mousePosition.y - PosY, dist.z);
Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
transform.position = worldPos;
}
}

有很多方法可以实现这一点。这是我想出的第一个方法。如果我们分解了可能构成快照的内容,我们可以召集一个脚本来附加到每个可快照的子项:

1( 将标签"父块"分配给您正在拖动的对象。
2( 将触发碰撞器附加到父对象和可捕捉子对象。
3( 当被拖动的对象进入碰撞区域时,将其捕捉到父对象。
4( 存储与父项的偏移量,以便在捕捉后保持其位置。

bool snapped = false;
GameObject snapparent; // the gameobject this transform will be snapped to
Vector3 offset; // the offset of this object's position from the parent
Update()
{
if (snapped == true)
{
//retain this objects position in relation to the parent
transform.position = parent.transform.position + offset;
}
}
void OnTriggerEnter(Collider col)
{
if (col.tag == "parentblock")
{
snapped = true;
snapparent = col.gameObject;
offset = transform.position - snapparent.transform.position; //store relation to parent
}
}

请记住,这只会将子对象对齐到您拖动的 1 个主父对象。不用说,您可能需要对其进行调整,以便它像您想要的那样专门针对您的项目执行,但希望这会让您朝着正确的方向前进。(仅供参考,我还没有测试过这个,所以我不保证它会在门外工作(

最新更新