2015-07-01 151 views
0

我在場景中有2個球體。我希望能夠將鼠標從一個球體拖放到另一個球體,並且在拖動時有一個指示器(例如一條直線)。釋放鼠標按鈕後,我想在第一個球體中存儲另一個球體(如GameObject)。在2個物體之間拖放gameObjects

我在UnityScript中需要這個,但我可以接受C#的想法。

到目前爲止,我還想過onMouseDown事件上的第一球,然後onMouseEnter到其他領域,我會保存在一些全局變量的數據(我唐諾如何做還)和onMouseExit我的情況下,只需將全局變量設置爲null即可。

然後onMouseUp在第一個球體上我將全局變量存儲在按下的對象(球體)中。

如何做到這一點的任何提示和技巧?

回答

1

Click and drag functionality demonstration

假設/設置

  1. 你在2D世界空間工作;拖動解決方案的這一部分的對象的邏輯將需要改變。

  2. 單擊拖動後設置父項,指的是將您沒有單擊的對象設置爲您單擊的父項的子項。

  3. 相機應該是正交相機;使用透視相機會導致拖動不符合您認爲應該的位置。

  4. 爲了進行拖動工作,我創建了一個用作2D場景「背景」的四邊形,並將其放在一個名爲「背景」的新圖層上。然後將圖層遮罩字段設置爲僅使用背景圖層。

  5. 創建和設置爲行渲染器的材料,(我使用顆粒/添加劑着色器用於上面的例子),並使用該線渲染器的參數我使用Start Width: 0.75End Width: 0,和確保Use World Space被勾選。

enter image description here

說明

首先設置的otherSphere字段是指向到場景的其他領域。 OnMouseDownOnMouseUp切換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); 
    } 
} 

希望這有助於某人。

+0

可能是我在Stackoverflow上得到的最佳答案。/jawdrop –