Implement movement snapping feature in PlayerController

This commit is contained in:
2025-12-12 22:16:24 +01:00
parent b6106cf82b
commit a6d486abb7

View File

@@ -12,6 +12,7 @@ namespace Infrastructure.Unity
[SerializeField] [SerializeField]
private float moveSpeed = 8f; private float moveSpeed = 8f;
[SerializeField] private float maxVelocityChange = 10f; [SerializeField] private float maxVelocityChange = 10f;
[SerializeField] private float snapForce = 15f;
[Header("Interaction")] [Header("Interaction")]
[SerializeField] private LayerMask tileLayer; [SerializeField] private LayerMask tileLayer;
@@ -56,7 +57,22 @@ namespace Infrastructure.Unity
private void HandleMovement() private void HandleMovement()
{ {
var targetVelocity = new Vector3(_moveInput.x, 0f, _moveInput.y) * moveSpeed; var targetVelocity = Vector3.zero;
var snapAxis = Vector3.zero;
if (_moveInput.sqrMagnitude > 0.1f)
{
if (Mathf.Abs(_moveInput.x) > Mathf.Abs(_moveInput.y))
{
targetVelocity = new Vector3(_moveInput.x > 0 ? moveSpeed : -moveSpeed, 0, 0);
snapAxis = Vector3.forward;
}
else
{
targetVelocity = new Vector3(0, 0, _moveInput.y > 0 ? moveSpeed : -moveSpeed);
snapAxis = Vector3.right;
}
}
var velocity = rb.linearVelocity; var velocity = rb.linearVelocity;
var velocityChange = (targetVelocity - velocity); var velocityChange = (targetVelocity - velocity);
@@ -66,6 +82,27 @@ namespace Infrastructure.Unity
velocityChange.y = 0f; velocityChange.y = 0f;
rb.AddForce(velocityChange, ForceMode.VelocityChange); rb.AddForce(velocityChange, ForceMode.VelocityChange);
if (snapAxis != Vector3.zero)
{
ApplySnapping(snapAxis);
}
else
{
ApplySnapping(Vector3.right);
ApplySnapping(Vector3.forward);
}
}
private void ApplySnapping(Vector3 axis)
{
var currentPos = Vector3.Dot(transform.position, axis);
var targetPos = Mathf.Round(currentPos);
var diff = targetPos - currentPos;
var correction = axis * (diff * snapForce);
rb.AddForce(correction, ForceMode.Acceleration);
} }
private void DetectGround() private void DetectGround()