Simple Exercises
Simple Exercises
First, create a flat surface and a green texture. Then, create a cube.
● Inside Assets folder from the Project window, create a new folder called Scripts.
● Go inside the Scripts folder, then Right click > Create > C# Script.
● Change the name to CubeController.
● Write down the following code and save it.
● Finally, attach the script to the Cube gameobject.
CubeController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
}
// Update is called once per frame
void Update()
{
}
}
B. Hello Earth!
RotateSphere.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
void Update()
{
// Apply horizontal rotation (around the Y-axis) to the sphere
transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
}
}
C. Box Collider
Now, add a new tag named Cube and assign it to the Cube gameobject.
To do that, select the Cube in the hierarchy.
Now, In the inspector, click Untagged and select Add Tag. Refer to the screenshots below.
Click on the Plus (+) sign.
Finally, Add a Rigidbody component to one or both objects. You can simply add Rigidbody
component to the sphere (earth).
Finally, create a new script named CollisionHandler and attach it to both sphere (earth) and the
cube.
CollisionHandler.cs
using UnityEngine;
Run the game. You should now be able to see that your cube can hit the earth and a message
appears upon hitting it.
”The asteroid has hit the earth!”
[BONUS]
using UnityEngine;
void Start()
{
// Get the Rigidbody component attached to the sphere
rb = GetComponent<Rigidbody>();
}
void Update()
{
// Check if the space key is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
// Apply an upward force to the sphere
rb.AddForce(Vector3.up * bounceForce, ForceMode.Impulse);
}
}
}