How can I drag a 2D object anywhere on the screen with the x axis? (touch)

What I would like, is a script where you can drag pretty much everywhere on the screen (maybe except for bottom and top of the screen) and the object would move only on the X axis…

You can drag anywhere, which means you don’t need to drag the object, you could drag under it if you needed.

Hello @Gooeygamer!
Have you tried searching Google? There are a bunch of great answers out there :slight_smile: If you don’t want to bother, here’s a script:

using UnityEngine;
using System.Collections;

public class TouchDrag : MonoBehaviour {
    public float speed = 0.1F;

    void Update() {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            transform.Translate(touchDeltaPosition.x * speed * Time.deltaTime, 0, 0);
        }
    }
}

Let me know if you don’t understand a part of this script :slight_smile:

1- add event system in your hierarchy
2- add physics 2d raycaster in main camera
3- add collider in main player which you want to drag left and right and put this script in this player
script is in the below -
this script only tested on 2D object for 2d game not tested on UI but you can try *

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

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

public static GameObject DraggedInstance;

Vector3 _startPosition;
Vector3 _offsetToMouse;
float _zDistanceToCamera;

#region Interface Implementations

public void OnBeginDrag(PointerEventData eventData)
{
    DraggedInstance = gameObject;
    _startPosition = transform.position;
    _zDistanceToCamera = Mathf.Abs(_startPosition.z - Camera.main.transform.position.z);

    _offsetToMouse = _startPosition - Camera.main.ScreenToWorldPoint(
        new Vector3(Input.mousePosition.x, Input.mousePosition.z, _zDistanceToCamera)
    );
}

public void OnDrag(PointerEventData eventData)
{
    if (Input.touchCount > 1)
        return;

    transform.position = Camera.main.ScreenToWorldPoint(
        new Vector3(Input.mousePosition.x, Input.mousePosition.z, _zDistanceToCamera)
        ) + _offsetToMouse;
}

public void OnEndDrag(PointerEventData eventData)
{
    DraggedInstance = null;
    _offsetToMouse = Vector3.zero;
}

#endregion

}