【问题标题】:how to snap two objects in runtime in unity?如何在运行时统一捕捉两个对象?
【发布时间】:2017-08-01 11:12:24
【问题描述】:

this is the 3d model i wanted to connect another model like this to its silver connectors on top side and also another model to right side(so do help me to snap it)我想知道如何在运行时将两个 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;
    }
}

【问题讨论】:

  • 取决于您想如何将它们对齐。在特定关节处连接它们?它们的位置是否完全相同?
  • 谷歌的捕捉逻辑?尝试弄清楚如何让对象对齐(可能是 x 和 z 阈值)
  • @lan H. 我已编辑,请务必查看。我想将另一个模型连接到其连接器的顶部,并将另一个模型连接到连接器的右侧。请帮忙
  • @bi0phaz3 是的,thanku.but 抱歉,我已经冲浪了一周了。让一切顺利

标签: c# unity3d unity5 mesh-collider


【解决方案1】:

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

1) 将标签“parentblock”分配给您拖动的对象。
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 个主父对象。不言而喻,您可能需要对其进行调整,以使其像您想要的那样专门针对您的项目执行,但希望这能让您朝着正确的方向前进。 (仅供参考,我尚未对此进行测试,因此不保证它会立即生效)

【讨论】:

  • 是的!谢谢,请检查已编辑的问题,我附上了图片@ryemoss
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 2023-03-15
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
相关资源
最近更新 更多