2016-08-21 88 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