- Home /
Character is bouncing infinitely after I implimented gravity
I am new to Unity. I used a tutorial from Single Sapling Games on youtube on how to make character movement. Everything was working until just after I implimented the gravity code, at which point the character began to bounce infinitely on the ground. Here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement : MonoBehaviour {
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
//Gravity
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
//REFERENCES
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
Move();
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if(isGrounded && velocity.y <0)
{
velocity.y = 2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
if (isGrounded)
{
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
//walk
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
//RUN
Run();
}
else if (moveDirection == Vector3.zero)
{
//IDLE
Idle();
}
moveDirection *= moveSpeed;
}
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
}
private void Walk()
{
moveSpeed = walkSpeed;
}
private void Run()
{
moveSpeed = runSpeed;
}
}
Answer by Hawaii_Dev · Apr 05 at 11:03 AM
Your boolean "isGrounded" return true when ever the character is touching the ground. The other check in the if statement "velocity < 2" will return true when the character controller is touching the ground. This means that once the character touches the ground both booleans will return true immediately. If it only should jump if the Spacebar is pressed add this to the if statement "Input.GetKeyDown(KeyCode.Space)" this ensures that the character is on the ground and also that you want the character to jump.
Your answer
Follow this Question
Related Questions
Player still Bouncing on moving down object while gravity and bounce are set properly?? 1 Answer
Phantom balls 0 Answers
Collisions are driving me mad! My sanity is fading fast... 3 Answers
Disabling useGravity issue 0 Answers
Object falling because of gravity and penetrating another object 2 Answers