
假設/設置
你在2D世界空間工作;拖動解決方案的這一部分的對象的邏輯將需要改變。
單擊拖動後設置父項,指的是將您沒有單擊的對象設置爲您單擊的父項的子項。
相機應該是正交相機;使用透視相機會導致拖動不符合您認爲應該的位置。
爲了進行拖動工作,我創建了一個用作2D場景「背景」的四邊形,並將其放在一個名爲「背景」的新圖層上。然後將圖層遮罩字段設置爲僅使用背景圖層。
創建和設置爲行渲染器的材料,(我使用顆粒/添加劑着色器用於上面的例子),並使用該線渲染器的參數我使用Start Width: 0.75
,End Width: 0
,和確保Use World Space
被勾選。

說明
首先設置的otherSphere
字段是指向到場景的其他領域。 OnMouseDown
和OnMouseUp
切換mouseDown布爾值,用於確定是否應更新線渲染器。這些也用於打開/關閉線渲染器,並設置/移除兩個球體的父變換。
要獲得被拖動的位置,我使用方法ScreenPointToRay從屏幕上的鼠標位置獲取光線。如果要爲此拖動功能創建添加平滑,則應在底部啓用if (...) else
語句,並將lerpTime設置爲一個值(對我來說,0.25可以很好地工作)。
注意;當你釋放鼠標時,父母立即被設置,因爲這樣的兩個對象最終都被拖拽了,但子女將無論如何都返回到它的前一個位置。
[RequireComponent(typeof(LineRenderer))]
public class ConnectedSphere : MonoBehaviour
{
[SerializeField]
private Transform m_otherSphere;
[SerializeField]
private float m_lerpTime;
[SerializeField]
private LayerMask m_layerMask;
private LineRenderer m_lineRenderer;
private bool m_mouseDown;
private Vector3 m_position;
private RaycastHit m_hit;
public void Start()
{
m_lineRenderer = GetComponent<LineRenderer>();
m_lineRenderer.enabled = false;
m_position = transform.position;
}
public void OnMouseDown()
{
//Un-parent objects
transform.parent = null;
m_otherSphere.parent = null;
m_mouseDown = true;
m_lineRenderer.enabled = true;
}
public void OnMouseUp()
{
//Parent other object
m_otherSphere.parent = transform;
m_mouseDown = false;
m_lineRenderer.enabled = false;
}
public void Update()
{
//Update line renderer and target position whilst mouse down
if (m_mouseDown)
{
//Set line renderer
m_lineRenderer.SetPosition(0, transform.position);
m_lineRenderer.SetPosition(1, m_otherSphere.position);
//Get mouse world position
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out m_hit, m_layerMask))
{
m_position.x = m_hit.point.x;
m_position.y = m_hit.point.y;
}
}
//Set position (2D world space)
//if (m_lerpTime == 0f)
transform.position = m_position;
//else
//transform.position = Vector3.Lerp(transform.position, m_position, Time.deltaTime/m_lerpTime);
}
}
希望這有助於某人。
可能是我在Stackoverflow上得到的最佳答案。/jawdrop –