Hello.
I’m making an FPS and decided to use the Character Controller component, not the asset. Whenever I look up with the camera, and I press W, the character will fly into the air for a few seconds before coming down again. Same thing happens if I look down and press S.
Is the problem in the code or somethink I should change in the inspector?
Thanks
void Update () {
if (cc.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump")){
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
cc.Move(moveDirection * Time.deltaTime);
The problem is that you’re applying movement that lifts the player off the ground.
If your object is looking up or down then your forward vector in Walk() is going to also be pointed up or down. You then call cc.Move(forward * Time.deltaTime) with that direction vector. So if you’re looking upwards then you’re telling the character controller to move upwards.
A simple way to avoid this could be to set the Y component of the forward vector to 0. However, doing this after you’ve applied input will mean that your character walks more slowly if you’re looking up or down, which you may not desire.
Personally I think I’d do something like this (untested):
Get forward direction.
“Flatten” it by setting Y to 0. (This assumes that you’re always walking on the X/Z plane. You’ll
need something more complicated if that’s not the case.)