Touchscreen Camera Movement in Unity

Implementing Basic Touch Controls

To handle touch input, you need to write a script that processes touch gestures and translates them into camera movements.

  1. Create a New Script:
  • In the Project window, right-click and select Create > C# Script.
  • Name the script TouchCameraController.
  1. 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 TouchCameraController script onto the Main Camera in the Inspector window.
  • Ensure the Camera component is assigned to the cam variable in the script.

Leave a comment

Your email address will not be published. Required fields are marked *