Cull length of ProjectOnPlane vector3 to bound of normal in direction of travel?
I'm currently attempting to slide my characterController around the edge of a collider. I'm using a series of raycasts that test if there is an edge directly in front of my capsule, and if so, I take the normal and use ProjectOnPlane to allow my capsule to slide around it.
forwardRay = transform.position + transform. forward * 0.1f;
RaycastHit hitInfo = default(RaycastHit);
var raycast = Physics.Raycast(forwardRay, Vector3.down, out hitInfo, Mathf.Infinity, 1);
if (raycast)
{
edgeNormal = Vector3.zero;
}
This casts a ray a little ahead forward: https://i.imgur.com/vqeXJVm.png
If we hit nothing, I cast a ray directly down beneath the capsule and get the hitpoint as the ground we're standing on: https://i.imgur.com/VoANLFz.png
else
{
RaycastHit hitInfo1 = default(RaycastHit);
var raycast1 - Physics.Raycast(transform.position, Vector3.down, out hitInfo1, Mathf. Infinity, 1);
if (raycast1)
{
ground = hitInfo1.point;
Then, I cast a ray back from the x/z of the forward (red) ray and the y of the ground (blue) ray (down slightly by -0.02f so it doesn't go straight over the top of the edge), back towards the hit point of the ground (blue) ray and store the normal: https://i.imgur.com/0wG7OEo.png
RaycastHit hitInfo2 = default(RaycastHit);
Physics.Raycast(new Vector3(forwardRay.x, ground.y + -0.02f, forwardRay.z), new Vector3((-transform.forward).x, 0f, (-transform.forward).z), out hitInfo2, Mathf.Infinity, 1);
edgeNormal = hitInfo2.normal;
}
}
I'm then moving characterController's Move() with my speed, in the direction I'm rotated, but using ProjectOnPlane to project my move vector onto the normal we grabbed with the third raycast:
GetComponent<CharacterController>().Move(Vector3.ProjectOnPlane(Quaternion.Euler(transform.eulerangles) * new Vector3(0f, gravity, currentSpeed), edgeVector) * Time.deltatime);
This works well enough for any edge, until we hit a corner: https://gfycat.com/delectableslipperygosling
I've created a mockup using invisible colliders to demonstrate exactly how I'd like it to work: https://gfycat.com/contentplayfulhyena
The trails are to demonstrate the motion I'd like. Is this possible at all to do?
Is it possible to shorten the length of a movement vector to the nearest bound of a normal?