2D Object Movement Touchpad Script for Unity



Hi there, in this post I’m going to share with you how to create a touchpad to control 2D object movements in Unity.

First step is to make an image UI element in your Unity Canvas. Then attach this script to it (name this script “MyMovementTouchpad”):

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

public class MyMovementTouchpad : MonoBehaviour
{
	public GameObject targetobject;

	public float mspeed = 0.05f;

	Vector2 currentMousePosition;
	Vector2 mouseDeltaPosition;
	Vector2 lastMousePosition;

	public static MyMovementTouchpad instance;

	[HideInInspector]
	public bool istouchpadactive;

	private void Start()
	{
		instance = this;
		ResetMousePosition();
	}

	public void ResetMousePosition()
	{
		if (Input.touchCount == 1)
		{
			currentMousePosition = Input.GetTouch(0).position;
		}
		else
		{
			currentMousePosition = Input.mousePosition;
		}

		lastMousePosition = currentMousePosition;
		mouseDeltaPosition = currentMousePosition - lastMousePosition;
	}

	void LateUpdate()
	{
		if (istouchpadactive)
		{
			if (Input.touchCount == 1)
			{
				currentMousePosition = Input.GetTouch(0).position;
			}
			else
			{
				currentMousePosition = Input.mousePosition;
			}

			mouseDeltaPosition = currentMousePosition - lastMousePosition;

			if (targetobject != null)
			{

				//action
				targetobject.transform.Translate(mouseDeltaPosition.x * mspeed, mouseDeltaPosition.y * mspeed, 0f);

			}

			lastMousePosition = currentMousePosition;


		}


	}

	public void ActivateTouchpad()
	{
		ResetMousePosition();
		istouchpadactive = true;
	}

	public void DeactivateTouchpad()
	{
		istouchpadactive = false;
	}
}

Then add event trigger to it. You need two triggers, on pointer up and pointer down. Use this game object itself as reference and call ActivateTouchpad() for pointer down, and DeactivateTouchpad() for pointer up.

The final step is to create a game object, and use it as targetobject.

I will show you a video to make it clearer:

loading...

Leave a Reply

Your email address will not be published.