2016-08-21 85 views
0

我想創建2D遊戲,當用戶拖動對象時,遊戲對象應該在單個軸(x軸)上跟隨鼠標。C# - 鼠標拖動遊戲對象在單個軸上跟隨鼠標。 2D

  1. 起點enter image description here

  2. 當我感動的是不應該去向上或向下。 enter image description here

這裏是我的代碼,但問題是,遊戲中的對象是繼鼠標到處我拖累。

using UnityEngine; 
using System.Collections; 
using UnityEngine.EventSystems; 

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { 

    public void OnBeginDrag(PointerEventData eventData) 
    { 
     Debug.Log("OnBeginDrag"); 
    } 

    public void OnDrag(PointerEventData eventData) 
    { 
     Debug.Log("OnDrag"); 

     this.transform.position = eventData.position; 
    } 

    public void OnEndDrag(PointerEventData eventData) 
    { 
     Debug.Log("OnEndDrag"); 
    } 
} 

回答

1

您正在改變所有軸(X,Y,Z)與this.transform.position = eventData.position;。只更改x軸。僅限使用eventData.position.x

public void OnDrag(PointerEventData eventData) 
{ 
    Debug.Log("OnDrag"); 
    Vector3 tempPos = this.transform.position; 
    tempPos.x = eventData.position.x; 
    this.transform.position = tempPos; 
} 
+0

Vector3呵呵我應該探索更多(y)。我可以問另一個問題嗎?是否也可以在拖拽時減慢速度並且有一定的限制,導致它將它拖拽爲重物。 – Perfectionist

+0

我不知道你的意思是減慢速度。由於這看起來不同的問題,爲什麼不創建一個新的問題,然後在這裏提供鏈接。我會看看。 – Programmer

+0

[鏈接](http://stackoverflow.com/questions/39083167/c-sharp-drag-and-then-drop-in-specified-area) 在這裏,先生。 (主)。 – Perfectionist