- Home /
I'm trying to allow my character to only jump when grounded
I'm trying to only allow my character to jump only while grounded and I'm not exactly sure how to do that any ideas on how I can implement it I don't really know coding that well.
//my code
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))] public class PlayerController : MonoBehaviour {
[SerializeField]
private float speed = 7f;
[SerializeField]
private float lookSensitivity = 3f;
[SerializeField]
private float jumpForce = 10.0f;
private PlayerMotor motor;
private Rigidbody rb;
private void Start()
{
motor = GetComponent<PlayerMotor>();
rb = GetComponent<Rigidbody>();
}
private void Update()
{
float xMov = Input.GetAxisRaw("Horizontal");
float zMov = Input.GetAxisRaw("Vertical");
Vector3 movHorizontal = transform.right * xMov;
Vector3 movVertical = transform.forward * zMov;
Vector3 movement = new Vector3(xMov, 0, zMov);
rb.AddForce(movement / speed);
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
Vector3 velocity = (movHorizontal + movVertical).normalized * speed;
motor.Move(velocity);
float yRot = Input.GetAxisRaw("Mouse X");
Vector3 rotation = new Vector3(0f, yRot, 0f) * lookSensitivity;
motor.Rotate(rotation);
float xRot = Input.GetAxisRaw("Mouse Y");
Vector3 cameraRotation = new Vector3(xRot, 0f, 0f) * lookSensitivity;
motor.RotateCamera(cameraRotation);
}
}
Answer by Dragate · Oct 27, 2017 at 05:27 PM
Declare your variable
bool isGrounded = true;
Modify your if statement
if (Input.GetKeyDown(KeyCode.Space) && isGrounded){
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
Add collision check function
void OnCollisionEnter (Collision collisionInfo){
isGrounded = true;
}
Your answer
Follow this Question
Related Questions
"Only assignment, call, increment, decrement and new object expressions can be used as statements" 1 Answer
Unloading Broken Assembly | How to solve this !? 2 Answers
How would I make a ListChangedEvent? 1 Answer
Unity 3D: How to make the gameobject speed increase continuously on tapping quickly? 1 Answer
Collider not registering hits? 4 Answers