Unity: Mobile Touch ControlsMoving a Character from Left to Right

Author Waldo
Published January 29, 2018

In this tutorial I show you how to make your character move left and right on mobile devices.

Video Walkthrough

While working on my latest game, I found it very difficult to find a tutorial that explained how to make a character move by tapping either the left or right side of the screen. My first strategy was to create two buttons, but then I discovered there is no press and hold function with native Unity buttons. So instead I had to build buttons to give you a visual reference (press down effect) and then I use the screens width as a way to detect finger position. Overall it ended up being very simple to do and I share that with you in this video.


Source Code

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

public class Movement : MonoBehaviour {
	//variables
	public float moveSpeed = 300;
	public GameObject character;

	private Rigidbody2D characterBody;
	private float ScreenWidth;


	// Use this for initialization
	void Start () {
		ScreenWidth = Screen.width;
		characterBody = character.GetComponent<Rigidbody2D>();
	}
	
	// Update is called once per frame
	void Update () {
		int i = 0;
		//loop over every touch found
		while (i < Input.touchCount) {
			if (Input.GetTouch (i).position.x > ScreenWidth / 2) {
				//move right
				RunCharacter (1.0f);
			}
			if (Input.GetTouch (i).position.x < ScreenWidth / 2) {
				//move left
				RunCharacter (-1.0f);
			}
			++i;
		}
	}
	void FixedUpdate(){
		#if UNITY_EDITOR
		RunCharacter(Input.GetAxis("Horizontal"));
		#endif
	}

	private void RunCharacter(float horizontalInput){
		//move player
		characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));

	}
}

Feedback is appreciated

As always if you have a better way of doing it, please let me and this community know in the comments.

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About