Game Creation with Unity – Part 4


In part 1 of this tutorial we started a new Unity 3D project to create a space game with the goal of shooting asteroids.

In part 2, we added the controls to our player/ship so that it can move within the environment as well as the objects that will become our asteroids and bullets.

In part3, we covered adding the script for the bullet, making explosions, and a little bit of troubleshooting.

In this final tutorial  we will setup the game for winning and losing and deploy the game for a web environment.

Video Clip:

[tubepress video=8XTMS31AGuI]

Scripts:

(Final) Player script:

var playerSpeed:int;

var bullet:Rigidbody;
var playerLives:int;
static var playerScore:int;

var xSpeed = 250.0;
var ySpeed = 120.0;

private var x = 0.0;
private var y = 0.0;

function Update () {
amtToMove = (playerSpeed * Input.GetAxis(“Vertical”)) *Time.deltaTime;
transform.Translate(Vector3.forward *amtToMove, Space.Self);

if (Input.GetMouseButton(1)) {
x+= Input.GetAxis(“Mouse X”) * xSpeed * 0.02;
y-= Input.GetAxis(“Mouse Y”) * ySpeed * 0.02;

var rotation = Quaternion.Euler(y,x,0);
transform.rotation = rotation;
}

if(Input.GetKeyDown(“space”) || Input.GetMouseButton(0)) {
var tempBullet:Rigidbody;
tempBullet=Instantiate(bullet, transform.position, transform.rotation);
}

if(playerScore >= 500)
{
Application.LoadLevel(3);
}
if(playerLives <=0) {
Application.LoadLevel(2);
}

}

function OnGUI() {
GUI.Label(Rect(10,10,200,50),”Score: “+ playerScore);
GUI.Label(Rect(10,30,200,50),”Lives: “+ playerLives);
}

function OnTriggerEnter(otherObject:Collider) {
if(otherObject.gameObject.tag ==”astroid”) {
Destroy(otherObject.gameObject);
playerScore +=100;
playerLives–;
}
}

Main Menu script:

function OnGUI(){
InstructionText=”Instructions:\nPress W and S to move\nRight Mouse to change Direction\nSpacebar to fire”;
GUI.Label(Rect(10,10,200,200),InstructionText);

if(GUI.Button(Rect(10,90,200,50),”Start Game”)) {
Application.LoadLevel(1);
}
}

Win Script:

function OnGUI() {
if(GUI.Button(Rect(10,10,300,50), “You Win! Press to Play Again”))

{
Application.LoadLevel(0);
}
}

Lose Script:

function OnGUI() {
if(GUI.Button(Rect(10,10,300,50),”You Lost. Press to Play again”))

{
Application.LoadLevel(0);
}
}

I want to thank TheLorax, whose tutorials on the Unity website inspired this tutorial.  Some of the scripts are directly derived from his tutorial.

Recent Posts