how to snap two objects in runtime in unity?

心已入冬 提交于 2019-12-08 06:03:49

问题


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)I want to know how to snap two 3D objects together in runtime. i.e during "play" the user must be able to dragup, down, left, right to snap one object with the other object .for example like "lego", ie. one 3D object should snap to another 3D object. How would I achieve this?

This is the code I use for dragging:

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:


There are many many ways to accomplish this. Here is the first method I came up with. If we break down what might comprise a snap, we can muster up a script to attach to each snappable child:

1) Assign tag "parentblock" to the object you are dragging around.
2) Attach a trigger collider to both the parent object and the snappable child object.
3) When the the dragged object enters the collision area, snap it to the parent.
4) Store the offset from the parent to maintain its position once snapped.

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
    }
}

Keep in mind this will only snap child objects to 1 master parent object that you are dragging around. It should go without saying you may need to tweak this for it to perform specifically to your project like you want, but hopefully this gets you in the right direction. (FYI I have not tested this so am not guaranteeing it will work right out of the gate)



来源:https://stackoverflow.com/questions/45436224/how-to-snap-two-objects-in-runtime-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!