C# script to make GameObject jump on pressed mouse button in 2D.
using System.Collections; using System.Collections.Generic; using UnityEngine; // ? 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class JumpOnClick : MonoBehaviour { public float jumpForce; public float timeBetweenJumps; private float timeBetweenJumpsCount; private Rigidbody2D myRigidbody2D; private bool canJump; private bool isGrounded; // Use this for initialization void Start () { myRigidbody2D = GetComponent<Rigidbody2D>(); canJump = true; isGrounded = true; timeBetweenJumpsCount = timeBetweenJumps; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0) && canJump && isGrounded) { myRigidbody2D.AddForce(Vector2.up * jumpForce); canJump = false; isGrounded = false; } if (!canJump) { timeBetweenJumps -= Time.deltaTime; if(timeBetweenJumps <= 0.0f) { timeBetweenJumps = timeBetweenJumpsCount; canJump = true; } } } void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Ground")) { isGrounded = true; } } }