0

I'm trying to create a 2d game and the game objects should follow the mouse on a single axis (the x axis), when the user drags the object.

  1. Starting Pointenter image description here

  2. When i moved that shouldnt go up or down. enter image description here

Here's my code, the problem is, the game object is following the mouse everywhere i drag.

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 Answer 1

1

You are currently changing all axis(x,y,z) with this.transform.position = eventData.position;. Only change the x-axis. Use eventData.position.x only.

public void OnDrag(PointerEventData eventData) { Debug.Log("OnDrag"); Vector3 tempPos = this.transform.position; tempPos.x = eventData.position.x; this.transform.position = tempPos; } 
Sign up to request clarification or add additional context in comments.

3 Comments

Vector3 huh i should explore more (y). can i ask another question? is it also possible to slow it down while dragging and have a limitation, cause im dragging it as a heavy object.
I don't know what you mean by slowing it down. Since this looks like different question, why not create a new question then provide the link here. I will take a look.
[link] (stackoverflow.com/questions/39083167/…) Here it goes, Sir. (Master).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.