Introduction
This article demonstrates how to create a rolling ball game with force and gravity using C# in Unity.
Prerequisites
Unity Environment version 5.6.1
Create Sphere
Step 1
First, you have to open the Unity project. Create terrain, trees, and water. Add skyboxes in your project. Create sphere into your game.
Right click on the Assets panel, select Create >> Material.
Material will be displayed in the Assets panel. Change the material color into yellow. Drag and drop the material into sphere.
Use gravity in your game
Step 2
Click on the sphere. Go to the Inspector window and click on "Add component". Select the "Physics" option.
Select RigidBody.
The rigid body will be added into the inspector panel. Tick on the "use gravity" checkbox to add Gravity in the sphere.
Go to Scripts. Right click on Scripts >> Create >> C# Scripts.
Rename the script as move. Drag and drop the move script into sphere. The default script will be displayed on the right side.
Go to the mono-development-Unity.
Write the code like the following.
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- [RequireComponent (typeof(Rigidbody))]
-
- public class move : MonoBehaviour {
-
- public float xForce = 10.0f;
- public float zForce = 10.0f;
- public float yForce = 500.0f;
-
-
-
- void Start () {
-
- }
-
- void Update () {
-
-
- float x = 0.0f;
- if (Input.GetKey (KeyCode.A)) {
- x = x - xForce;
- }
-
- if (Input.GetKey (KeyCode.D)) {
- x = x + xForce;
- }
-
-
-
- float z = 0.0f;
- if (Input.GetKey (KeyCode.S)) {
- z = z - zForce;
- }
-
- if (Input.GetKey (KeyCode.W)) {
- z = z + zForce;
- }
-
-
- float y= 0.0f;
- if (Input.GetKeyDown (KeyCode.Space)) {
- y = yForce;
- }
-
- GetComponent<Rigidbody> ().AddForce (x, y, z);
- }
- }
Save the program.
Come back to the Unity window. Click on the “Play” button. The sphere will be displayed.
Press the “W” key. The ball will be moved forward.
Press “A, S, D” respectively to move the ball in left, right, backward, and rolling the ball. Press the “Space bar” and the ball will jump.
Click on the GameObject and select 3D Object >>Cube.
Create Cube
Step 3
Increase the cube size using scale tool, like the following.
Set the main camera like below.
Rolling ball game with force and gravity
Step 4
Now, click on the “Play” button. The game view will be displayed.
You can play the game using “W, A, S, D” keys. The ball will be rolling in the cube.
Press the “space bar” and the ball will jump up.
Release the “space bar” to get the ball in the cube again.
Summary
I hope you understood how to create a rolling ball game with force and gravity using scripts in Unity.