In this tutorial, you will learn how to write a script in C# code that allows your player to jump only when they are touching the ground.
Watch the video below and scroll down to view the sample code.
Sample code
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public float speed = 5f; public float jumpSpeed = 8f; private float movement = 0f; private Rigidbody2D rigidBody; public Transform groundCheckPoint; public float groundCheckRadius; public LayerMask groundLayer; private bool isTouchingGround; // Use this for initialization void Start () { rigidBody = GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { isTouchingGround = Physics2D.OverlapCircle (groundCheckPoint.position, groundCheckRadius, groundLayer); movement = Input.GetAxis ("Horizontal"); if (movement > 0f) { rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y); } else if (movement < 0f) { rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y); } else { rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y); } if(Input.GetButtonDown ("Jump") && isTouchingGround){ rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed); } } }
Next tutorial: Changing the player sprite