Implement movement snapping feature in PlayerController
This commit is contained in:
@@ -12,6 +12,7 @@ namespace Infrastructure.Unity
|
||||
[SerializeField]
|
||||
private float moveSpeed = 8f;
|
||||
[SerializeField] private float maxVelocityChange = 10f;
|
||||
[SerializeField] private float snapForce = 15f;
|
||||
|
||||
[Header("Interaction")]
|
||||
[SerializeField] private LayerMask tileLayer;
|
||||
@@ -56,7 +57,22 @@ namespace Infrastructure.Unity
|
||||
|
||||
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 velocityChange = (targetVelocity - velocity);
|
||||
@@ -66,6 +82,27 @@ namespace Infrastructure.Unity
|
||||
velocityChange.y = 0f;
|
||||
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user