Please help me out here. I am using a character controller for the player and even with downwards force it wont fully reach the ground and the collider itself is not touching the ground. When I start my game the player spawns touching the ground, but when I start walking it starts floating again.
Like 5cm off the ground. Jumping works fine but it also lands 5cm higher.
here is the movement script for the player:
using Unity.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
// I hate feds
public class PlayerMovementScript : MonoBehaviour
{
[Header("Character Controller")]
private CharacterController controller;
[Header("Movement Values")]
[SerializeField] private float walkSpeed;
[SerializeField] private float sprintSpeed;
//how fast we get to sprint
[SerializeField] private float sprintTransitSpeed = 5f;
//actual speed of the player
private float speed;
private Vector2 _moveDirection;
[Header("Jumping Values")]
public bool canJump = false;
[SerializeField] private float jumpHeight = 3f;
[SerializeField] private float gravity = 9.81f;
[SerializeField] private float groundDistance = 0.2f;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundMask;
private bool isGround;
private float verticalVelocity;
[Header("Player Input")]
[SerializeField] private InputActionReference moveInput;
private InputAction m_jumpAction;
private InputAction m_sprintAction;
[Header("Crouch Fix")]
[SerializeField] private PlayerCrouchingScript crouchingScript;
[SerializeField] private float normalHeight;
void Awake()
{
controller = GetComponent<CharacterController>();
m_jumpAction = InputSystem.actions.FindAction("Jump");
m_sprintAction = InputSystem.actions.FindAction("Sprint");
}
// Update is called once per frame
void Update()
{
Movement();
}
private void Movement()
{
GroundMovement();
}
private void GroundMovement()
{
//Gets the direction in a vector2 format makes it into a vector3 with y as gravity then moves
_moveDirection = moveInput.action.ReadValue<Vector2>();
Vector3 _move = transform.right * _moveDirection.x + transform.forward * _moveDirection.y;
if(m_sprintAction.IsPressed() && _move.magnitude > 0)
{
//increases to sprint
speed = Mathf.Lerp(speed, sprintSpeed, sprintTransitSpeed * Time.deltaTime);
}
else
{
//decreases to walk
speed = Mathf.Lerp(speed, walkSpeed, sprintTransitSpeed * Time.deltaTime);
}
if(_move.magnitude <= 0)
{
speed = walkSpeed;
}
_move *= speed;
_move.y = PlayerGravityCalculation();
controller.Move(_move * Time.deltaTime);
}
private float PlayerGravityCalculation()
{
if(controller.isGrounded)
{
//gets the player down
verticalVelocity = -1f;
isGround = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(m_jumpAction.WasPressedThisFrame() && isGround && canJump)
{
//jump height calculation
verticalVelocity = Mathf.Sqrt(jumpHeight * gravity * 2);
}
}
else
{
//falling
verticalVelocity -= gravity * Time.deltaTime;
}
return verticalVelocity;
}
}
