- Home /
* SOLVED * Convert Input.GetAxis("Horizontal") to Touch Drag with Width Control
public float speed = 100;
public Rigidbody2D rb;
public void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Add touch support
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Touch touch = Input.touches[0];
h = touch.deltaPosition.x;
v = touch.deltaPosition.y;
}
//Move only if we actually pressed something
if ((h > 0 || v > 0) || (h < 0 || v < 0))
{
Vector3 tempVect = new Vector3(h, v, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
//rb.MovePosition(rb.transform.position + tempVect);
Vector3 newPos = rb.transform.position + tempVect;
checkBoundary(newPos);
}
}
void checkBoundary(Vector3 newPos)
{
//Convert to camera view point
Vector3 camViewPoint = Camera.main.WorldToViewportPoint(newPos);
//Apply limit
camViewPoint.x = Mathf.Clamp(camViewPoint.x, 0.04f, 0.96f);
camViewPoint.y = Mathf.Clamp(camViewPoint.y, 0.07f, 0.93f);
//Convert to world point then apply result to the target object
Vector3 finalPos = Camera.main.ViewportToWorldPoint(camViewPoint);
rb.MovePosition(finalPos);
}
SOLVED! I removed the Vertical control but this works really nice. https://stackoverflow.com/questions/49726677/unity-2d-convert-input-getaxishorizontal-to-touch-drag-with-width-control
How do you change the code in FixedUpdate() be in touch control. so when I drag the object(my player) it will follow in the Horizontal axis only BUT! it will not go off the boundaries.
Answer by Cornelis-de-Jager · Apr 09, 2018 at 06:31 AM
// Change this
Input.GetAxis('Horizontal');
// To this
CrossPlatformInputManager.GetAxis('Horizontal');
This was working fine but I needed buttons to use it. Is there a way to direct touch my object or anywhere in the screen and use it to drag?
Your answer
Follow this Question
Related Questions
Simultaneous Touch Drag Controls 0 Answers
Unity2D touch screen input 0 Answers
Help With Multitouch in 2D Windows Store apps 0 Answers
Touch drag 2D object in x axis 1 Answer
Drag-and-drop dot on mobile 2D 0 Answers