Hello!
I’m trying to use Vector3.ProjectOnPlane
in order to implement wall-slide movement. However there is one case where the ProjectOnPlane
method does not return a correct Vector3
, causing the character to be stuck.
If I collide with a cube with the following rotations, the returned Vector3
is not parallel to the surface as we can see with the Debug.DrawRay
.
Here is my code:
private Vector3 GetBounceMovement(Vector3 initialMovement, Vector3 currentMovement, Vector3 currentPosition, int depth)
{
if (depth >= 2)
{
return Vector3.zero;
}
var centerOfSphere1 = currentPosition - Vector3.up * ((col.height - 1) / 2);
var centerOfSphere2 = currentPosition + Vector3.up * ((col.height - 1) / 2);
Physics.CapsuleCast(centerOfSphere1, centerOfSphere2, col.radius, currentMovement, out RaycastHit hit, 0.2f);
if (hit.transform && hit.transform != transform)
{
var remaining = currentMovement;
var magnitude = remaining.magnitude;
remaining = Vector3.ProjectOnPlane(remaining, hit.normal).normalized;
remaining.y = 0;
remaining *= magnitude;
if (depth == 0)
Debug.DrawRay(transform.position, remaining * 50, Color.red, 0.5f);
return GetBounceMovement(initialMovement, remaining, currentPosition, depth + 1);
}
else
{
return currentMovement;
}
}
Any help would be appreciated!