Looking Hyper
- thetperson314
- Aug 20, 2021
- 1 min read

This script will help you to create movement using the mouse or touch (in android).
This type of movement is one of the most common in hyper casual games.
The code consists of 3 main parts:
Getting the mouse position (if in editor)
Getting the finger position (if in android)
moving the player according to the position
using UnityEngine;
public class PlayerMovementScript : MonoBehaviour
{
public float speed = 10f;
Vector3 mouseLastPos = Vector3.zero;
public float barrierXmin = -4f;
public float barrierXMax = 4f;
Rigidbody rigidbody;
void Start()
{
rigidbody = GetComponent<Rigidbody();
}
void Update()
{
#if UNITY_ANDROID && !UNITY_EDITOR
if (Input.touchCount > 0)
{
Vector3 fingerPos = Input.touches[0].position;
fingerPos.z = 10;
fingerPos = Camera.main.ScreenToWorldPoint(fingerPos);
if (mouseLastPos == Vector3.zero)
{
mouseLastPos = fingerPos;
}
fingerPos = new Vector3(fingerPos.x, this.transform.position.y, this.transform.position.z);
MovePlayer(fingerPos, barrierXmin, barrierXMax);
}
else
{
mouseLastPos = Vector3.zero;
}
#endif
#if UNITY_EDITOR
if (Input.GetMouseButton(0))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
if (mouseLastPos == Vector3.zero)
{
mouseLastPos = mousePos;
}
mousePos = new Vector3(mousePos.x, this.transform.position.y, this.transform.position.z);
MovePlayer(mousePos, barrierXmin, barrierXMax);
}
else
{
mouseLastPos = Vector3.zero;
}
#endif
}
/// <summary>
/// Moving the player in between the min and max X positions
/// </summary>
/// <param name="mousePos">In World Point</param>
/// <param name="barrierMin">The x position</param>
/// <param name="barrierMax">The x position</param>
public void MovePlayer(Vector3 mousePos, float barrierMin, float barrierMax)
{
int dir = 0;
dir = (mouseLastPos.x < mousePos.x) ? 1 : -1;
float xPos = this.transform.position.x + Mathf.Abs(mouseLastPos.x - mousePos.x) * dir;
xPos = Mathf.Clamp(xPos, barrierMin, barrierMax);
this.transform.position = new Vector3(xPos, this.transform.position.y, this.transform.position.z);
mouseLastPos = mousePos;
}
}