Unity Swipe Input Creation
Unity Swipe Input Creation
Hello everyone, in this post I will explain how to create Swipe Input in Unity, a method commonly used in mobile games, especially endless runner games.
using UnityEngine;
// ReSharper disable once CheckNamespace
namespace UrhobA.Inputs.Swipe
{
public class MouseMovement : MonoBehaviour
{
private Vector2
_startedPos, // We take the position where the mouse is first clicked
_secondPos, // We take the position where the mouse is released
_currentPos; // We get the current mouse position
private Direction.Direction _returnedValue; // We keep the value to be returned
public Direction.Direction GetValue() // Function to access the current position
{
return _returnedValue;
}
public void ResetValue() // Function to reset the current position
{
_returnedValue = Direction.Direction.None;
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
_startedPos = Input.mousePosition; // When the mouse is first clicked, we get its position
if (!Input.GetMouseButtonUp(0)) return; // As long as the mouse button is not released, we return.
_secondPos = Input.mousePosition; // We get the position at the moment the mouse is released
_currentPos = new Vector2(_secondPos.x - _startedPos.x, _secondPos.y - _startedPos.y); // We make the necessary calculations and assign as the current mouse position
_currentPos.Normalize(); // We normalize it.
// Down below, we're sending the mouse positions.
if (_currentPos.y > 0 && _currentPos.x > -0.5f && _currentPos.x < .5f)
_returnedValue = Direction.Direction.Up;
if (_currentPos.y < 0 && _currentPos.x > -0.5f && _currentPos.x < .5f)
_returnedValue = Direction.Direction.Down;
if (_currentPos.x < 0 && _currentPos.y > -0.5f && _currentPos.y < .5f)
_returnedValue = Direction.Direction.Left;
if (_currentPos.x > 0 && _currentPos.y > -0.5f && _currentPos.y < .5f)
_returnedValue = Direction.Direction.Right;
}
}
}
// ReSharper disable once CheckNamespace
namespace UrhobA.Inputs.Swipe.Direction
{
// We are creating an enum value to send our directions
public enum Direction
{
None,
Left,
Right,
Up,
Down
}
}
We use our code as follows.
MouseMovement _mouseMovement;
awake(){
_mouseMovement = new MouseMovement(); // It is better to add it using add component here.
}
switch(_mouseMovement.GetValue()){
case Direction.Left:
// Slide left codes..
// If you don't want it to keep happening forever
_mouseMovement.ResetValue();
// Enter the command.
break;
case Direction.Right:
// Slide right codes..
break;
}
As I mentioned above, you can use it in your project.
You can use the link below to go to the GitHub page of the code.


Yorum Gönder