Artificial Intelligence
Please fill the required field.

unity 3d c# player controller if touching ground and pressed spacebar then jump


using UnityEngine; public class PlayerController : MonoBehaviour { public float jumpForce = 5f; // the force of the jump public bool isGrounded; // a check for if the player is touching the ground private Rigidbody rb; // the Rigidbody component of the player // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody>(); // set the rb variable to the Rigidbody component of the player } // Update is called once per frame void Update() { if (isGrounded && Input.GetKeyDown(KeyCode.Space)) // check if the player is grounded and if the Spacebar is pressed { rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); // add upward force to the rigidbody } } // check for collisions with the ground private void OnCollisionStay(Collision collision) { if (collision.gameObject.CompareTag("Ground")) // check if the collision is with an object with the "Ground" tag { isGrounded = true; // set isGrounded to true } } // check when exiting a collision private void OnCollisionExit(Collision collision) { if (collision.gameObject.CompareTag("Ground")) // check if the collision is with an object with the "Ground" tag { isGrounded = false; // set isGrounded to false } } }