Create a rolling ball game with force and gravity

This tutorial will show you how to create a simple rolling ball game using the Rigidbody physics component in unity to add force and gravity. In this game, we will use the W,A,S,D keys to move the ball left and right, and backwards and forwards. We will also use the Space key to make the ball jump up and gravity will bring the ball back down, as seen in the animated GIF below.


Watch the video below to see how you can create a simple rolling ball game with force and gravity. Then scroll down to take a look at the sample code.

Here is the sample code in C# for this game.

using UnityEngine;
using System.Collections;
// Simple Rolling Ball Game code - 18 Oct 2015 Daniel Wood
// Add this code to a script called 'move' and then attach the script to a sphere in your game
[RequireComponent (typeof(Rigidbody))]
public class move : MonoBehaviour {
 public float xForce = 10.0f;
 public float zForce = 10.0f;
 public float yForce = 500.0f;
 // Use this for initialization
 void Start () {
 // Update is called once per frame
 void Update () {
 // this is for the X axis' movement (moving left and right)
 float x = 0.0f;
 if (Input.GetKey (KeyCode.A)) {
 x = x - xForce;
 if (Input.GetKey (KeyCode.D)) {
 x = x + xForce;
 // this is for the Z axis' movement (moving backwards and forwards)
 float z = 0.0f;
 if (Input.GetKey (KeyCode.S)) {
 z = z - zForce;
 if (Input.GetKey (KeyCode.W)) {
 z = z + zForce;
 // this is for the Y axis' movement (jumping)
 float y = 0.0f;
 if (Input.GetKeyDown (KeyCode.Space)) {
 y = yForce;
 GetComponent<Rigidbody> ().AddForce (x, y, z);

This a simple game with no scoring or other objects to interact with, but you could easily extend the game by adding a user interface, scoring, different cameras, and objects to interact with. As an example, you could make a simple pinball game.