So, I’m trying to make a character snap to a ground collision mesh that I have, and snap it’s up vector to that of the normal face it’s colliding with. What I’ve got so far seems to work…sort of. I’ve got character collider with a basic script on it, and in the script I’m using the OnControllerColliderHit function to detect collision with the ground. It looks like this:
void OnControllerColliderHit (ControllerColliderHit hit) {
if(hit.gameObject.CompareTag("Ground")) {
Vector3 groundNormal = hit.normal;
float tiltAngle = Vector3.Angle(myTransform.up, groundNormal);
Vector3 tiltVector = Vector3.Cross(groundNormal, myTransform.up);
myTransform.rotation = Quaternion.identity;
myTransform.RotateAround(myTransform.position, tiltVector, -tiltAngle);
myTransform.position = hit.point;
}
}
So, when my character controller collides with my ground, I use the normal of the hit, and rotate my characters up vector to that. This seems to work for about one frame, the my character wigs out, and falls through the ground. My update loop isn’t doing much aside from applying gravity, it’s really basic, and based off some sample unity code:
void Update () {
Vector3 movement = new Vector3(0, 0, 0);
if(!myCharacter.isGrounded)
{
// Apply gravity to our velocity to diminish it over time
velocity.y += Physics.gravity.y * Time.deltaTime;
// Adjust additional movement while in-air
movement.x *= inAirMovementScale;
movement.z *= inAirMovementScale;
}
movement += velocity;
movement += Physics.gravity;
movement *= Time.deltaTime;
// Actually move the character
myCharacter.Move( movement );
if ( myCharacter.isGrounded )
{
velocity = Vector3.zero;
}
}
Anyone have any input as why this could be happening? I can’t quite figure it out.
Many thanks in advance!