In this tutorial you will learn how to write a script to make your player jump in a 2D game with C# code in Unity. In the following tutorial, you will learn how to make the player 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; // Use this for initialization void Start () { rigidBody = GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { 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")){ rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed); } } }
Next tutorial: Jumping with ground check