I know this question has been asked before. The problem is that the answers don’t really help me or I don’t understand them. So I’m writing my own code. I need my charactercontroller to stay grounded when it walks down a slope. If I could create a Raycast variable then I could probably finish the code but I’m not sure if that’s even possible, I tried but got an error. Anyway, here’s my code.
var distToFloor : float = 1.3;
var isFloored : boolean;
function Update()
{
Floored();
print(isFloored);
}
function Floored()
{
if(Physics.Raycast(transform.position, Vector3.down, distToFloor))
{
isFloored = true;
}
else
{
isFloored = false;
}
}
What I want to achieve now is to snap my character to the floor so that he is grounded whenever isFloored is true. I don’t want to increase my gravity to achieve this because it’ll cause other problems.
You can use the alternate overload of Physics.Raycast that fills out a RaycastHit class for you. Then, you can use this RaycastHit class to determine where that ray intersected the ground. You can use this position as the place to put the character’s feet:
void Floored()
{
RaycastHit raycastResult;
if (Physics.Raycast(transform.position, Vector3.down, out raycastResult, distToFloor))
{
// this assumes the character's feet are at transform.position. You might
// need to adjust this up or down to account for where transform.position should
// be relative to the floor...
transform.position = raycastResult.point;
isFloored = true;
}
else
{
isFloored = false;
}
}
Just noticed that your question was in uJS. The relevant section in uJS looks like:
var raycastResult : RaycastHit;
if (Physics.Raycast(transform.position, Vector3.down, raycastResult, distToFloor) {
transform.position = raycastResult.point;
// rest of the code snippet omitted.
The code that’s in your comment is very similar to this. Here’s the code from your comment translated into unityscript:
var controller : CharacterController = GetComponent(CharacterController);
var snapDistance : float = 1.1f; //Adjust this based on the CharacterController's height and the slopes you want to handle - my CharacterController's height is 1.8
var hitInfo : RaycastHit; // note, you don't need to allocate a new RaycastHit() here. You don't need to do that in the C# code either. It's done automatically by Physics.Raycast().
if (Physics.Raycast(new Ray(transform.position, Vector3.down), hitInfo, snapDistance)) {
isGrounded = true;
transform.position = hitInfo.point; // note: this line seems redundant. It can (and probably should be) deleted.
transform.position = new Vector3(hitInfo.point.x, hitInfo.point.y + controller.height / 2, hitInfo.point.z);
} else {
isGrounded = false;
}