- Home /
Jumping not always work
Got the following script off the Character Controller doc page and it's working only sometimes. I disabled rigid body because it was messing with the rotation of the object, making it rotating like wild. Below is the code:
public class PlayerController : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private float playerSpeed = 2.0f;
private float jumpHeight = 1.0f;
private float gravityValue = -9.81f;
private void Start()
{
controller = gameObject.AddComponent<CharacterController>();
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
// Changes the height position of the player..
if (Input.GetButtonDown("Jump") && groundedPlayer)
{
print("Jump button pressed");
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
}
The jumping here only works sometimes. The object is not always considered grounded so when the jump button pressed it's usually ignored. Though the object is constantly changing state and sometimes actually gets grounded so that jump triggers. Also, all objects are simply set in the scene in 10 by 10 area, with the player object being in 0 0 0 coordinates, yet it moves a bit when I run the game, I feel like that could cause the issue here.
Any suggestions?
Answer by dtbrown0801 · Jan 13, 2021 at 12:26 AM
Hi. Did it work with the rigid body enabled? Because if it did in the constraints you can freeze the rotation of all axis and the position of every axis except the y (unless you want it to move around strangely).
Answer by TelionFondrad · Jan 13, 2021 at 04:29 PM
Hi, it's still jumping only sometimes, while spinning wild. I returned back the rigidbody component as the dtbrown0801 recommended. Check out the console. It logs when Jump button is pressed and when jump is actually initiated. I also checked the .isGrounded value on every frame. Apparently it looks like true false false false... true... etc. Basically, it's changing its state for some reason all the time. Why would that happen?
Vid: https://i.gyazo.com/7596d77cb54349ca95f57f44e72a7aef.mp4