Implementing Basic Touch Controls
To handle touch input, you need to write a script that processes touch gestures and translates them into camera movements.
- Create a New Script:
- In the Project window, right-click and select
Create > C# Script. - Name the script
TouchCameraController.
- Script for Basic Camera Movement:
using UnityEngine;
public class TouchCameraController : MonoBehaviour
{
public Camera cam;
private Vector2 oldTouchPosition;
void Update()
{
if (Input.touchCount == 1)
{
if (oldTouchPosition == null)
{
oldTouchPosition = Input.GetTouch(0).position;
}
else
{
Vector2 newTouchPosition = Input.GetTouch(0).position;
Vector2 delta = (Vector2)oldTouchPosition - newTouchPosition;
cam.transform.Translate(new Vector3(-delta.x, -delta.y, 0) * Time.deltaTime);
oldTouchPosition = newTouchPosition;
}
}
else
{
oldTouchPosition = null;
}
}
}
Attach the Script to the Camera:
- Select the Main Camera in the Hierarchy window.
- Drag the
TouchCameraControllerscript onto the Main Camera in the Inspector window. - Ensure the Camera component is assigned to the
camvariable in the script.