My character can jump infinitely How would I fix this?
I was trying to make a game in unity and I was following Brackeys tutorial on first person movement but my character can jump infinitely. (I started recently, and I've look at fixes online but I being the noob I am couldn't understand any of them)
public class PlayerMovement : MonoBehaviour { public CharacterController controller;
public float speed = 12f;
Vector3 velocity;
public float gravity = -9.8f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Comment
Hi, I changed some bits in your script and it seems to be working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player$$anonymous$$ovement : $$anonymous$$onoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.01f;
public Layer$$anonymous$$ask ground$$anonymous$$ask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, ground$$anonymous$$ask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -6f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.$$anonymous$$ove(move * speed * Time.deltaTime);
if(Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = $$anonymous$$athf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.$$anonymous$$ove(velocity * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
How to stop my character from infinite jumping? 2 Answers
Player Infinitely jumps... 0 Answers
Player Is infinite jumping 1 Answer
Hello! I have infinite jump problem, please help me! 0 Answers
how to stop infinite jumping in air? 0 Answers