- Home /
How does character controller check slopes?
Does anyone know how the character controller checks slopes? It must somehow because it has a slope limiter that keeps you from walking up something too steep if it's set up that way. I ask because I want a lazy fix to slowing my character if they go up a steep incline, and was thinking something like:
speed = desiredSpeed - desiredSpeed * controller.slope / 90;
Obviously the only problem with this is that the controller.slope variable doesn't exist in that form. I'm trying my best to avoid raycasts to check slope if I can find out how the controller checks slope and just take that variable.
Answer by K-e-n · Jun 05, 2021 at 04:54 PM
Look at this link: normal The normal is the up direction of the surface you hit. Normals are always normalized: (0f, 1f, 0f), it is basically scaled down so the highest values is 1. The normal of the top of a table (an average table) would be (0f, 1f, 0f). The normal for the side of a wall (a flat 90 degree wall) would be (1f, 0f, 0f) if the side of the wall was in the positive x direction.
A 45 degree slope would have a normal of (a, 0.5f, b) and (a + b = 0.5f). A normal has a total of 1f. The important thing is that the y is 0.5f. If you multiply this by 90 (to get the angle of the slope): (a, 0.5f * 90f, b) = (a, 45, b). This would be the slope.
void Update()
{
RaycastHit hit;
hit = Physics.Raycast(transform.position, -transform.up, 0.2f, layer);
//this next line will work
float speed = hit.normal.y * 90f;
//as well as this one
float speed = hit.normaly.y;
}
I get the normal of the down raycast. Then, I multiply it by 90f (you do not have to. It is just easier to visualize the angle). A flat surface would have a hit.normal.y of 1f, so a speed of 90f. A 45 degree surface would have a y of 0.5f, so a speed of 45f. The higher the slope, the slower the player.
Important: this was untested, and the second/third paragraph might be slightly wrong. In case it was, at least you know what a normal is, it you can hopefully do what you wanted.