- Home /
Player falls through terrain when using crouching script?
I have a crouching script that allows me to change the player height when I press the C button and return to the original height when that button is released, but upon releasing the button I fall through the terrain. This only happens when I am stationary, if I am moving it works correctly. How can I fix this so I can crouch in one position?
var walkSpeed : float = 7;
var crouchSpeed : float = 3;
private var charMotor : CharacterMotor;
private var charController : CharacterController;
private var theTransform : Transform;
private var charHeight : float;
function Start ()
{
charMotor = GetComponent(CharacterMotor);
theTransform = transform;
charController = GetComponent(CharacterController);
charHeight = charController.height;
}
function Update ()
{
var h = charHeight;
var speed = walkSpeed;
if (Input.GetKey("c"))
{
h = charHeight*0.5;
speed = crouchSpeed;
}
charMotor.movement.maxForwardSpeed = speed;
var lastHeight = charController.height;
charController.height = Mathf.Lerp(charController.height, h, 5*Time.deltaTime);
theTransform.position.y += (charController.height-lastHeight)/2;
}
You should way your character's collider in scene view when trying to crouch. The problem could be that when you are resizing the character that its collider is scaling down through the terrain, preventing collision detection. In that case, you would need to move the character upwards while resizing to compensate.
Resize the same way you already are just move the character upwards at the same time so that when resizing the collider it doesn't intersect the terrain.
How would I go about moving the player upwards? I have looked around but I can't find a way to do it
transform.position += Vector3.up * Time.deltaTime;
The code I've provided is generic and may not suit your needs. Let me know how it goes.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
itween move to do not end(even it is) 0 Answers
Fps Aiming Script help 2 Answers