Creating Unity Swerve Input
Creating Unity Swerve Input
Hello everyone, in this post I will show you what kind of code should be written for the Swerve mechanic in Unity.
I am leaving the code below and, with comment lines, I will explain what we are doing at each part.
using UnityEngine;
// ReSharper disable once CheckNamespace
namespace UrhobA.Inputs.Swerve
{
public class Mouse : MonoBehaviour
{
private Vector2
_startedPos, // position where the movement started
_delta; // position where the movement continues
private Vector2 _value; // the value reflected as a result of the movement
public Vector2 GetValue() // This function will be called from the script where we write our character movement and will be included in the movement code.
{
return _value;
}
public float maxDistance = 100f; // the maximum amount the user's movement can be
#region System Functions
private void Update()
{
if (Input.GetMouseButtonDown(0))
_startedPos = (Vector2) Input.mousePosition; // we get the starting position
if (Input.GetMouseButtonUp(0))
{
// We reset values when the movement is over
_delta = Vector2.zero;
_startedPos = Vector2.zero;
_value = Vector2.zero;
}
if (!Input.GetMouseButton(0)) return; // if it's moving, we do the calculations
_delta = (Vector2) Input.mousePosition - _startedPos;
_delta.x = Mathf.Clamp(_delta.x, -maxDistance, maxDistance);
_delta.y = Mathf.Clamp(_delta.y, -maxDistance, maxDistance);
_value = _delta / maxDistance;
_startedPos = (Vector2) Input.mousePosition;
}
#endregion
}
}
You can check the project's source code at the GitHub link below.


Yorum Gönder