- Home /
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.
Answer by LightningStorm102 · Jan 02, 2019 at 08:45 PM
Hello @Gooeygamer! Have you tried searching Google? There are a bunch of great answers out there :) 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 :)
Your answer
Follow this Question
Related Questions
How to drag around an object and making it collide with other object 2D 2 Answers
Creating a custom runtime scaler !? 0 Answers
OnBeginDrag, OnEndDrag not being called for unknown reasons 1 Answer
How can I add constraints to a Rect Transform position? 0 Answers
Split screen in half - Touch Controls 3 Answers