C# script to make GameObject jump on pressed mouse button in 2D.

Content not available.
Please allow cookies by clicking Accept on the banner

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;
        }
    }
}

 



Unity 2D C# Jump On Click
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close