Introduction
In this article, we discuss how to make mobile touch controls and move a character from left to right using C# scripts in Unity.
Prerequisites
Unity Environment version 2018.4.19f1
Create the 2D project in Unity.
Now open up main.Assets. Import the 2D Character for the Unity. Drag the Scene view onto your view controller.
Select 2D Character and go to the Drag n Drop Scene view in Unity.
Create a Button in your project.
Click on the "GameObject" menu in the menu bar. Select Create UI (Button). The Create Button will be added to the scene View.
Rename the Button as Left button.
Create a DuplicateButton in your project.
Select the button and type the keys (Ctrl + D). The Create Duplicate Button will be added to the scene View.
Rename the Duplicate Button as the Right button.
Create a C# Script
Right-click on Assets. Select Create >> C# script.
Rename the script as Movement.
Write the code like the following.
Double click on the Movement. The MonoDevelop-Unity editor will open up.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Movement: MonoBehaviour {
-
- public float moveSpeed = 300;
- public GameObject character;
- private Rigidbody2D characterBody;
- private float ScreenWidth;
-
- void Start() {
- ScreenWidth = Screen.width;
- characterBody = character.GetComponent < Rigidbody2D > ();
- }
-
- void Update() {
- int i = 0;
-
- while (i < Input.touchCount) {
- if (Input.GetTouch(i).position.x > ScreenWidth / 2) {
-
- RunCharacter(1.0 f);
- }
- if (Input.GetTouch(i).position.x < ScreenWidth / 2) {
-
- RunCharacter(-1.0 f);
- }
- ++i;
- }
- }
- void FixedUpdate() {
- #if UNITY_EDITOR
- RunCharacter(Input.GetAxis("Horizontal"));
- #endif
- }
- private void RunCharacter(float horizontalInput) {
-
- characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
- }
- }
Save the Program.
Go back to the Unity window. Drag and drop the movement script onto the MainCamera.
Drag and drop the 2D character onto the Movement script.
Click on the Play button. Press the “Left touch ” and “Left Arrow ” key. The 2D character will move to the Left side.
Click on the Play button. Press the “Right touch ” and “Right Arrow ” key. The 2D character will move to the Right side.
Summary
I hope you understood how to make mobile touch controls and move a character from left to right using C# scripts in Unity.