I want to stop my player from jumping in midair but i don’t know how to use a bool. Does anyone know how to stop this with my script?
My script:
{
float leftRight;
float jump;
public float speed;
public float jumpSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// Assigns inputs
leftRight = Input.GetAxis("Horizontal");
jump = Input.GetAxis("Jump");
// Jump & walk
transform.Translate(Vector3.right * Time.deltaTime * speed * leftRight);
transform.Translate(Vector3.up * Time.deltaTime * jumpSpeed * jump);
& I’m a beginner & I want to keep my script about the same.
You need a way to check if the player is grounded. There are a few ways to do this one of which is ray or sphere casting and checking for the ground.
It really depends on your game which technique is most appropriate but most approaches are just evaluating if the player is grounded. and using that the clause for an if statement to allow for the jumping action i.e.
if(!IsGrounded && Input.GetButtonDown("Jump")) {
Jump();
}
You have to check if you are grounded like this:
if (characterController.isGrounded == true)
{
// jump
}
and to reference your character controller do this
CharacterController characterController;
void Start()
{
characterController = GetComponent<CharacterController>();
}
Hope this helps!
@Mikepopularpro
Hello!
Here is my code should work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody playerRB;
public float jumpForce = 10;
public float gravityModifier;
public bool isOnGround = true;
// Start is called before the first frame update
void Start()
{
playerRB = GetComponent<Rigidbody>();
Physics.gravity *= gravityModifier;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space) && isOnGround)
{
playerRB.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
}
private void OnCollisionEnter(Collision collision)
{
isOnGround = true;
}
}
Hope it worked
.
.
.
.
PS: Make sure you add a rigid body and I am using C#
You need to add a ground check so something like
private isGrounded;