0% found this document useful (0 votes)
20 views

Final Game Programming

The document outlines 9 practical assignments for learning DirectX 11: 1) Setup DirectX 11 and initialize a Direct3D device 2) Draw a triangle using buffers, shaders and HLSL 3) Texture the triangle using Direct3D 11 4) Use programmable diffuse lighting to light the triangle 5) Demonstrate spotlight lighting using DirectX11 6) Load 3D models and render them in DirectX 11 7) Build a 2D UFO game using Unity 8) Make a 3D space shooter game using Unity tutorials 9) Make a 3D sphere game using Unity tutorials
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Final Game Programming

The document outlines 9 practical assignments for learning DirectX 11: 1) Setup DirectX 11 and initialize a Direct3D device 2) Draw a triangle using buffers, shaders and HLSL 3) Texture the triangle using Direct3D 11 4) Use programmable diffuse lighting to light the triangle 5) Demonstrate spotlight lighting using DirectX11 6) Load 3D models and render them in DirectX 11 7) Build a 2D UFO game using Unity 8) Make a 3D space shooter game using Unity tutorials 9) Make a 3D sphere game using Unity tutorials
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

1

INDEX
DATE TOPIC SIGNATURE
PRACTICAL 1 :
Setup DirectX 11, Window
Framework and Initialize
Direct3D Device

PRACTICAL 2:
Buffers, Shaders and HLSL
(Draw a triangle using
Direct3D 11)

PRACTICAL 3:
(Texture the Triangle using
Direct 3D 11)

PRACTICAL 4:
Lightning (Programmable
Diffuse Lightning using
Direct3D 11)

PRACTICAL 5:
Demonstrating spotlight using
DirectX11 and rendering

PRACTICAL 6:
Loading models into DirectX
11 and rendering

PRACTICAL 7:
Build a 2D UFO game with
the help of unity.

PRACTICAL 8:
Make a 3D game Space
Shooter with the help of the
unity tutorials

PRACTICAL 9:
Making a 3D sphere game
with the help of the unity
tutorials

Practical #1
2

Note: Error –using Microsoft.DirectX

Sol: References-Browse-C:-Windows—Microsoft.Net—DirectX For Manage Code—


1.0.2903.0—Select 3 file –Microsoft.DirectX.dll + Microsoft.DirectX.Direct3D.dll +
Microsoft.DirectX.Direct3DX.dll

Error: An unhandled exception of type 'System.BadImageFormatException' occurred in


System.Windows.Forms.dll
Sol: Go to Properties –Build setx86 instead of AnyCPU

Aim: Setup DirectX 11, Window Framework and Initialize Direct3D Device

To use the DirectX Diagnostic Tool to determine the version of DirectX that is installed on
your computer, follow these steps:

1. Click Start, and then click Run.


2. Type dxdiag, and then click OK.
3. On the System tab, note the version of DirectX that is displayed on the DirectX Version
line.
4. On the various tabs, check the version information for each DirectX file.
5. When you are finished checking file versions, click Exit.

Steps how to download DirectX:

1. Visit the DirectX download page on Microsoft's site.


2. Click the red Download button and then the blue Next button to save the setup file to your
computer.
3. Complete the DirectX installation by following directions from Microsoft's website or from
the DirectX installation program.
4. Restart your computer, even if you're not prompted to do so.
5. After restarting your computer, test to see if updating to the latest version of DirectX corrected
the problem you were having.

Source Code:-
using System;
using System.Collections.Generic;
3

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Device device = null;
public Form1()
{
InitializeComponent();
InitDevice();
}
public void InitDevice()
{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Reference, this,
CreateFlags.SoftwareVertexProcessing, pp);
}
protected override void OnPaint(PaintEventArgs e)
{
device.Clear(ClearFlags.Target, Color.CornflowerBlue, 0, 1);
device.Present();
}
}
}

Output

Practical #2

Aim: Buffers, Shaders and HLSL (Draw a triangle using Direct3D 11)

Source Code
4

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingMicrosoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace MDDX
{
public partial class Form2 : Form
{
Microsoft.DirectX.Direct3D.Device device;
public Form2()
{
InitializeComponent();
InitDevice();
}
private void InitDevice()
{
PresentParameterspp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing,
pp);
}
private void Render()
{
CustomVertex.TransformedColored[] vertexes = new CustomVertex.TransformedColored[3];
vertexes[0].Position = new Vector4(240, 110, 0, 1.0f);//first point
vertexes[0].Color = System.Drawing.Color.FromArgb(0, 255, 0).ToArgb();
vertexes[1].Position = new Vector4(380, 420, 0, 1.0f);//second point
vertexes[1].Color = System.Drawing.Color.FromArgb(0, 0, 255).ToArgb();
vertexes[2].Position = new Vector4(110, 420, 0, 1.0f);//third point
vertexes[2].Color = System.Drawing.Color.FromArgb(255, 0, 0).ToArgb();
device.Clear(ClearFlags.Target, Color.CornflowerBlue, 1.0f, 0);
device.BeginScene();
device.VertexFormat = CustomVertex.TransformedColored.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertexes);
device.EndScene();
device.Present();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
Render();
}
5

}
}

Output
6

Practical #3

Aim: Texturing (Texture the Triangle using Direct 3D 11)

Source Code

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingMicrosoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespaceTexture_Triangle
{
public partial class Form1 : Form
{
private Microsoft.DirectX.Direct3D.Device device;
privateCustomVertex.PositionTextured[] vertex = new CustomVertex.PositionTextured[3];
private Texture texture;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
PresentParameterspp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0,DeviceType .Hardware
,this,CreateFlags.HardwareVertexProcessing ,pp);
device.Transform.Projection = Matrix.PerspectiveFovLH(3.14f / 4,
device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 20), new Vector3(), new
Vector3(0, 1, 0));
device.RenderState.Lighting = false;
vertex[0] = new CustomVertex.PositionTextured(new Vector3(0, 0, 0), 0, 0);
vertex[1] = new CustomVertex.PositionTextured(new Vector3(5, 0, 0), 0, 1);
vertex[2] = new CustomVertex.PositionTextured(new Vector3(0, 5, 0),-1, 1);
texture=new Texture (device,new Bitmap ("E:\\AAG\\game
programming\\DirectXPro\\Texture_Triangle\\Texture_Triangle\\me.jpg"),0,Pool.Managed );
}

private void Form1_Paint(object sender, PaintEventArgs e)


{
7

device.Clear(ClearFlags.Target, Color.CornflowerBlue, 1, 0);


device.BeginScene();
device.SetTexture(0,texture);
device.VertexFormat = CustomVertex.PositionTextured.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList, vertex.Length / 3, vertex);
device.EndScene();
device.Present();
}
}
}

Output
8

Practical #4

Aim: Lightning (Programmable Diffuse Lightning using Direct3D 11)

Source Code

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingMicrosoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace Lightning
{
public partial class Form1 : Form
{
private Microsoft.DirectX.Direct3D.Device device;
privateCustomVertex.PositionNormalColored[] vertex = new
CustomVertex.PositionNormalColored[3];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PresentParameterspp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
device.Transform.Projection = Matrix.PerspectiveFovLH(3.14f / 4,
device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 10), new Vector3(), new
Vector3(0, 1, 0));
device.RenderState.Lighting = false;
vertex[0] = new CustomVertex.PositionNormalColored(new Vector3(0,1,1),new
Vector3(1,0,1),Color.Red.ToArgb());
vertex[1] = new CustomVertex.PositionNormalColored(new Vector3(-1, -1, 1), new
Vector3(1, 0, 1), Color.Red.ToArgb());
vertex[2] = new CustomVertex.PositionNormalColored(new Vector3(1, -1, 1), new
Vector3(-1, 0, 1), Color.Red.ToArgb());
device.RenderState.Lighting = true;
device.Lights[0].Type = LightType.Directional;
device.Lights[0].Diffuse = Color.Plum;
device.Lights[0].Direction = new Vector3(0.8f,0,-1);
9

device.Lights[0].Enabled = true;
}

private void Form1_Paint(object sender, PaintEventArgs e)


{
device.Clear(ClearFlags.Target, Color.CornflowerBlue, 1, 0);
device.BeginScene();
device.VertexFormat = CustomVertex.PositionNormalColored.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList, vertex.Length / 3, vertex);
device.EndScene();
device.Present();
}

}
}

Output

Practical #5

Aim: Demonstrating spotlight using DirectX11 and rendering


10

Source Code

namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private Device device;
private float angle = 0f;
public Form2()
{
InitializeComponent();
InitializeDevice();
this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.Opaque, true);
}
public void InitializeDevice()
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.SoftwareVertexProcessing, presentParams);
device.RenderState.CullMode = Cull.None;
device.RenderState.Lighting = true;
device.Lights[0].Type = LightType.Spot;
device.Lights[0].Range =4;
device.Lights[0].Position = new Vector3(0,-1,0f);
device.Lights[0].Enabled = true;
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI
/ 4, this.Width / this.Height, 1f, 50f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 30), new
Vector3(1, 0, 0), new Vector3(0, 5, 0));
CustomVertex.PositionNormalColored[] vertices = new
CustomVertex.PositionNormalColored[6];
vertices[0].Position = new Vector3(10f, 12f, 0f);
vertices[0].Normal = new Vector3(0, 2, 0.5f);
vertices[0].Color = Color.Yellow.ToArgb();
vertices[1].Position = new Vector3(-5f, 5f, 0f);

vertices[1].Normal = new Vector3(0, 2, 0.5f);


vertices[1].Color = Color.Blue.ToArgb();
vertices[2].Position = new Vector3(5f, 5f, -1f);
vertices[2].Normal = new Vector3(0, 0, 0.5f);
vertices[2].Color = Color.Pink.ToArgb();
vertices[3].Position = new Vector3(5f, -5f, -1f);
vertices[3].Normal = new Vector3(0, 0, 0.5f);
vertices[3].Color = Color.Green.ToArgb();
11

vertices[4].Position = new Vector3(10f, 12f, 0f);


vertices[4].Normal = new Vector3(0, 0, 0.5f);
vertices[4].Color = Color.Green.ToArgb();
device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0);
device.BeginScene();
Vector3 v;
device.VertexFormat = CustomVertex.PositionNormalColored.Format;
device.Transform.World = Matrix.Translation(-5, -10 * 1 / 3, 0) *
Matrix.RotationAxis(new Vector3(), 0);
Console.WriteLine(device.Transform.World.ToString());
device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 3, vertices);
device.EndScene();
device.Present();
this.Invalidate();
;
}
}
}

Output
12

Practical #6

Aim: Loading models into DirectX 11 and rendering

Source Code

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingMicrosoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace MDDX
{
public partial class Form4 : Form
{
Microsoft.DirectX.Direct3D.Device device;
Microsoft.DirectX.Direct3D.Texture texture;
Microsoft.DirectX.Direct3D.Font font;
public Form4()
{
InitializeComponent();
InitDevice();
InitFont();
LoadTexture();
}
private void InitFont()
{
System.Drawing.Font f = new System.Drawing.Font("Arial", 16f, FontStyle.Regular);
font = new Microsoft.DirectX.Direct3D.Font(device, f);
}
private void LoadTexture()
{
texture = TextureLoader.FromFile(device,
"F:\\Mudassar\\GP\\DXPractical\\MDDX\\Twilight_Frost_by_Phil_Jackson.jpg", 400, 400, 1, 0,
Format.A8B8G8R8, Pool.Managed, Filter.Point, Filter.Point, Color.Transparent.ToArgb());
}
private void InitDevice()
{
PresentParameterspp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing,
pp);
}
13

private void Render()


{
device.Clear(ClearFlags.Target, Color.CornflowerBlue, 0, 1);

device.BeginScene();
using (Sprite s = new Sprite(device))
{
s.Begin(SpriteFlags.AlphaBlend);
s.Draw2D(texture, new Rectangle(0, 0, 0, 0), new Rectangle(0, 0, device.Viewport.Width,
device.Viewport.Height), new Point(0, 0), 0f, new Point(0, 0), Color.White);
font.DrawText(s, "Mudassar Ansari", new Point(0, 0), Color.White);
s.End();
}
device.EndScene();
device.Present();
}
private void Form4_Paint(object sender, PaintEventArgs e)
{
Render();
}
}
}

Output

Practical # 7
14

Aim: Build a 2D UFO game with the help of unity.

Steps:

1.Launch Unity and Unity Launch Dialouge Box will appear which allows you to select the existing file or
start with new file → Select new file → Give any name and path to the new file and select the 2d.

2. The unity application will be launched with the new file → we will be doing UFO game whose files are
already in unity asset store, so will open asset store and download and import the essentials files.

For opening assert store Go to Windows option →General → Asset store OR press Ctrl + 9 → Expand
the asset store window opened → Select Unity Essential → Sample Project → 2D UFO Tutorial →
Download the assets and import all the assets downloaded → Save scene in a particular file.
15

3. Go to Sprites folder in bottom left in Project window → Select background → Drag and drop it in the
Hierarchy window.

4.Now select the Background in the hierarchy window → Details will appear in the Inspector window →
Reset.

5. Go to the Gizmos option in Scene window and deselect the ‘show gird line’.

Now we have added the background of the game, now we add the player from the sprit folder as we did
for background i.e drag and drop the player/UFO from the sprit folder in the hierarchy window → In
Inspector window reset it too.
16

6. In Inspector window → Sprit renderer → Sorting Layer → Player for the Player/UFO and Background
option for the Background.

In ‘sorting layer’ the layer option at the top is the last layer from the screen or the gamer and the layer
option at the end is the top most layer which appears at the top of all layers.

For e.g.: here background is back most and player is the top most.

7. Change the size of the player to suitable size → Scale → X = 0.75; Y = 0.75

Select Main Camera → Size → set size such how that the whole background is seen → Even change
color → Background → RGB = 32.
17

8. UFO/player → Inspector window → Add component → Physics 2D → Rigid Body 2D →Gravity = 0

Again add component → Script →Complete Player Controller.

9. Select Background in hierarchy window → In inspector window → Add component → Physics 2D →


Box Collider 2D → Duplicate it three times → set values such as it makes the four walls of the
background → Size : X = 3.3 , Y = 31.64 and set the offsets.
18

10. Select sprit from project window → Drag and drop pickups in hierarchy window → sorting layer =
Pickup → Deselect the player temporarily while working with the pickup.
19

11. Add component → Physics 2D → Circle collider 2D to pickup → radius = 0.94. → Is trigger selected.

Add component → Scripts → Complete rotator.

Add component → Physics 2D → Rigid Body 2D → Body type →Kinematic.

Drag and drop the pickup from hierarchy to the Prefab folder in project window.

Now copy the pickup you made and duplicate it few more times to get enough pickups.
20

12. Select Main Camera → Add component → Script → Complete Camera Controller → Now drag and
drop the player object in the script player option.

13. Now for the game running select the prefab pickup →In Inspector window → Tag → Pickup

Now select Player →In Inspector window → Tag → Player


21

14. Now we will count the score and End the game

For this:

In Hierarchy → Create → UI → Text → Rename it as CountText.

By doing so we will get three objects Canvas, Text, EventSystem in which Text is the child of Canvas

15. Select Text → Anchor → Press Shift and Alt button together and select the left top corner

16. Now for ending game text → Hierarchy window → Create → UI → Text.

Rename text as End Text → reset.


22

17. Now select player → script –> Drag and drop the CountText in Count Text option in script of player.

And even Drag and drop the EndText in Win Text option in script of player.

Save scenes after every successful operations.

18. Finally game is completed so let’s build the game for PC and standalone devices.

For that:

File → Build Settings → Build settings dialogue box will appear → Select the PC, MAC, Linus Standalone
option and select the scene to be build and then build and run.
23

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::All Scripts:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

CompletePlayerController.cs

using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.


using UnityEngine.UI;

public class CompletePlayerController : MonoBehaviour


{

public float speed; //Floating point variable to store the player's movement speed.
public Text countText;
//Store a reference to the UI Text component which will display the number of pickups collected.
public Text winText;
//Store a reference to the UI Text component which will display the 'You win' message.

private Rigidbody2D rb2d;


//Store a reference to the Rigidbody2D component required to use 2D Physics.
private int count;
//Integer to store the number of pickups collected so far.

// Use this for initialization


24

void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();

//Initialize count to zero.


count = 0;

//Initialze winText to a blank string since we haven't won yet at beginning.


winText.text = "";

//Call our SetCountText function which will update the text with the current value for count.
SetCountText ();
}

//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");

//Store the current vertical input in the float moveVertical.


float moveVertical = Input.GetAxis ("Vertical");

//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move
our player.
rb2d.AddForce (movement * speed);
}

//OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.


void OnTriggerEnter2D(Collider2D other)
{
//Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
if (other.gameObject.CompareTag("PickUp"))

//... then set the other object we just collided with to inactive.
other.gameObject.SetActive(false);

//Add one to the current value of our count variable.


count = count + 1;

//Update the currently displayed count by calling the SetCountText function.


SetCountText ();
}
25

//This function updates the text displaying the number of objects we've collected and displays our victory
message if we've collected all of them.
void SetCountText()
{
//Set the text property of our our countText object to "Count: " followed by the number stored in our
count variable.
countText.text = "Count: " + count.ToString ();

//Check if we've collected all 12 pickups. If we have...


if (count >= 12)
//... then set the text property of our winText object to "You win!"
winText.text = "You win!";
}
}

CompleteCameraController.cs

using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

public GameObject player; //Public variable to store a reference to the player game object

private Vector3 offset; //Private variable to store the offset distance between the player and
camera

// Use this for initialization


void Start ()
{
//Calculate and store the offset value by getting the distance between the player's position and
camera's position.
offset = transform.position - player.transform.position;
}

// LateUpdate is called after Update each frame


void LateUpdate ()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the
calculated offset distance.
transform.position = player.transform.position + offset;
}
}
26

CompleteRotator.cs
using UnityEngine;
using System.Collections;

public class CompleteRotator : MonoBehaviour {

//Update is called every frame


void Update ()
{
//Rotate thet transform of the game object this is attached to by 45 degrees, taking into account
the time elapsed since last frame.
transform.Rotate (new Vector3 (0, 0, 45) * Time.deltaTime);
}
}
27

Practical #8

Aim: Make a 3D game Space Shooter with the help of the unity tutorials

Steps:

1. Launch Unity → Create new file → Name it as Space Shooter → select 3D.

2. The unity application will be launched with the new file → we will be doing Space Shooter game
whose files are already in unity asset store, so will open asset store and download and import the
essentials files.
For opening assert store Go to Windows option → General → Asset store OR press Ctrl + 9 →
Expand the asset store window opened → Select Unity Essential → Sample Project →3D Space
Shooter Tutorial → Download the assets and import all the assets downloaded → Save scene in a
particular file.
28

3. We will be making the game for web


Select File → Build settings → Build setting dialogue box appears → Select WebGL→ Switch
Platform

Click Project Settings →in Inspector window → Resolution → width = 600, height = 900 → save scene.

4. Assets → Model →
Player ship → Drag and drop it in Hierarchy Window → Rename it as Player → In Inspector window
→ Reset it → Add Component → Physics → Rigid Body → After selecting rigid body; in rigid body
options → deselect Gravity
Again Add Component → Physics → Mesh Collider → In mesh collider options, Is trigger Select it.
29

5. In project window → assets → prefabs → engines → Drag it and make it the child of the Player

6. Our Player is looking horizontal in game view To make it view vertical have to change Main Camera
Main Camera → Reset → Change the Position, rotation, camera type, size in the inspector window
such as it player looks as the way we want. Even Change the Clear Flags to solid Color and
background make it black
30

7. Now we put some lights in the game → In Hierarchy window → Create → Light → Directional
light → rename it as Main Light → Reset it → Change its rotation as X = 20, Y = -115 and
Intensity = 1.5

8. Duplicate the Main Light → rename it as fill light → reset → rotation → X = 5, Y = 125;
Intensity = 1 → Color = R =128, G = 192, B =192.

9. Duplicate the fill light → rename it rim light → reset → rotate → Y = 65, X = -15 → color =
white → Intensity = 0.5

10. Now Put Background to the scene → Create → Quad → rename it as background → reset →
rotate it at X = 90
31

Remove mesh collider →in project window → assets → textures → tilenebulagreen image →
drag and drop on the quad → resize the quad such as it covers the whole scene
To give Background proper Lighting → Defuse → Unlit → Texture.

11. Now we move the player → Select Player → Add component → New Script →
Player_Controller
And write the code to move the player → give speed as 10 in script option.

12. Now we add the bolt fire for the player → create → 3D object → Quad → rename it as bolt →
rotate it at X = 90 → Drag the laser_orange from the texture folder to the bolt → remove the
mesh collider
Add component → physics → rigid body → deselect the use gravity option
Again add component → physics → capsule collider → adjust it such as it covers the whole bolt
→ select the is trigger option
Add component → new scripts → name it as mover → save and add → write code to make it
move → give speed = 20 in script speed option.
32

13. Save it and drag and drop it in the prefab folder and the delete it from the hierarchy window
14. We have to position the bolt such as it fires from the front of the spaceship on trigger
Create → Empty game object → rename Shot Spawn → make it as a child of Player → position it
in the front of the Spaceship.
Even select the player script and drag and drop the shot spawn object in the Shot Spawn script
option and put the value 0.25 in the fire rate option
33

15. Now we make Boundary so as the bolt strikes this boundary it destroys rather than staying it in
the game and increasing the size
Create → 3D → Cube → rename boundary → reset → is trigger selected →position it such as it
covers the whole background→ Add component → New script → name it as
Destroy_by_boundary and save and add → write the code so the bolts and everything just get
destroys on contact of boundary.

16. Now we make the obstacles asteroid


Create → Empty game object → rename asteroid → reset → add component → physics → rigid
body → deselect use gravity → angular drop = 0
Add component → physics → capsule collider → adjust it such as it covers the whole asteroid
Add component → New Script → name rotator → save and add→write the suitable code for it
Add component →New Script → name destroy on contact → save and add → write the suitable
code for it.
34

17. Now we add little animation of explosions


Prefab → VFX → Explosions → drag and drop this files in the script of the asteroid options

18. Add component in asteroid →new script → name mover → put the value 20 in speed option in
script → Drag and drop it in the prefab folder and delete it from the hierarchy window

19. Now we add the game controller to the game which will make waves of asteroids, fire bolts on
click and even count score, end game and restart it.
Create → empty game object → rename it as gamecontroller → reset → tag it as gamecontroller
→ add component → new script → name gamecontroller → write suitable code → put values to
the options in the script
35

20. Add audio to the game


Select Audio in project window → deselect the 3D sound option in every sound we going to use
Directly drag it on the asteroid prefab and select stay on awake
Drag on the player and deselect the stay on awake
Drag the background audio on the gamecontroller and select the play on awake and loop
36

21. Now we create the Score count, end game and reset game
Create → GUI Text → rename Score text → text as Score: → position X= 0, Y = 1, Z = 0 →
Pixel offset X = 10, Y = -10
37

Create → GUI Text → rename restart → position X = 1, Y = 1; Anchor = upper right; Alignment
= right; Pixel X= -10, Y =-10; Text = restart.

Create → GUI Text → rename Game Over → Position X = 0.5, Y = 0.5; Anchor = Center;
Alignment = center
Now drag and drop the score text in scoretext option and restart in restart option in script of
gamecontroller

22. Finally game is completed so let’s build the game for PC web
For that:
File → Build Settings → Build settings dialogue box will appear →Select the scene to be build
and then build and run.

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: All Scripts :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


PlayerController.cs

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour


{
public float speed;
38

public float tilt;


public Boundary boundary;

public GameObject shot;


public Transform shotSpawn;
public float fireRate;

private float nextFire;

void Update ()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
audio.Play ();
}
}

void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);


rigidbody.velocity = movement * speed;

rigidbody.position = new Vector3


(
Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
);

rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);


}
}

Mover.cs

using UnityEngine;
using System.Collections;

public class Mover : MonoBehaviour


{
public float speed;
39

void Start ()
{
rigidbody.velocity = transform.forward * speed;
}
}

DestroyByBoundary.cs

using UnityEngine;
using System.Collections;

public class DestroyByBoundary : MonoBehaviour


{
void OnTriggerExit(Collider other)
{
Destroy(other.gameObject);
}
}

RandomRotator.cs

using UnityEngine;
using System.Collections;

public class RandomRotator : MonoBehaviour


{
public float tumble;

void Start ()
{
rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
}
}

DestroyByContact.cs

using UnityEngine;
using System.Collections;

public class DestroyByContact : MonoBehaviour


{
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private GameController gameController;
40

void Start ()
{
GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent <GameController>();
}
if (gameController == null)
{
Debug.Log ("Cannot find 'GameController' script");
}
}

void OnTriggerEnter(Collider other)


{
if (other.tag == "Boundary")
{
return;
}
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
gameController.GameOver ();
}
gameController.AddScore (scoreValue);
Destroy(other.gameObject);
Destroy(gameObject);
}
}

GameController.cs

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour


{
public GameObject hazard;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;

public GUIText scoreText;


41

public GUIText restartText;


public GUIText gameOverText;

private bool gameOver;


private bool restart;
private int score;

void Start ()
{
gameOver = false;
restart = false;
restartText.text = "";
gameOverText.text = "";
score = 0;
UpdateScore ();
StartCoroutine (SpawnWaves ());
}

void Update ()
{
if (restart)
{
if (Input.GetKeyDown (KeyCode.R))
{
Application.LoadLevel (Application.loadedLevel);
}
}
}

IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x),
spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);

if (gameOver)
{
restartText.text = "Press 'R' for Restart";
restart = true;
42

break;
}
}
}

public void AddScore (int newScoreValue)


{
score += newScoreValue;
UpdateScore ();
}

void UpdateScore ()
{
scoreText.text = "Score: " + score;
}

public void GameOver ()


{
gameOverText.text = "Game Over!";
gameOver = true;
}
}

DestroyByTime.cs
using UnityEngine;
using System.Collections;

public class DestroyByTime : MonoBehaviour


{
public float lifetime;

void Start ()
{
Destroy (gameObject, lifetime);
}
}
43

Practical # 9

Aim: Making a 3D sphere game with the help of the unity tutorials

Steps:

1. Launch Unity and Unity Launch Dialouge Box will appear which allows you to select the
existing file or start with new file → Select new file → Give any name and path to the new file
and select the 3D

2. Now first we make a plane as background to the game For that:


Hierarchy window → 3D object → Plane → Rename it as background → reset.

Even we see grid lines in the preview, but we don’t need it. So for removing grid lines

Scene window → Gismos → deselect the show grid option.


44

3. Scale the Background by selecting it in hierarchy window


→ In Inspector window scale → X = 2 Y = 1 Z = 2.

4. We made Background now we need a player.


In Hierarchy window → Create → 3D object → Sphere →
rename it as player → reset

As we place the new player we only see the half sphere as both
the plane and sphere have same coordinates. So we will change
a little y axis of sphere to see the full sphere

Inspector window → Position → Y = 0.5


45

5. Now we give some colors to make game attractive


Project window → Create → Folder → rename it as Materials → Selecting Materials Folder →
Create → Material → rename Background → Select Background material → In Inspector window
→ Albedo → Change color e.g. R = 0, G = 32, B = 64 → Drag the material to the Background Plane.

6. Select Directional Light → In Inspector window → rotation → Y = 60.


46

7. Select player → Inspector window → Add component →


Physics → Rigid Body.
Again add component → New Script → Player Controller →
Create and Add.

8. Click on Player_Controller Script and edit it by following


code.

9. Now we adjust the main camera


Select Main Camera → Inspector window → Rotation: X = 45;
Position: X= 0, Y = 10, Z = -13

Add Component →New Script → Player Controller → Create


and Add.
47

Open Script for editing and type code.

10. Now we make the walls for the Player so that it does fall off from the ground
Hierarchy → 3D object → cube.

In inspector →scale: X = 0.5, Y = 2, Z = 20.5

Make four walls and arrange them at the four ends of the plane background
48

11. Select create from hierarchy window →3D object → Cube →

12. Add component →New Script→ rename Rotator → Create


and add.
Write code:

Drag and drop the pickup from hierarchy to the Prefab folder in project window.

Now copy the pickup you made and duplicate it few more times to get enough pickups.
49

13. Now select the Pickup and drag


and drop it into the prefab folder
In Hierarchy window → Tag →
Pickup and Even we select the is
trigger option in Box Collider

For player select the tag player.

14. Now we put the Count Text and the


Win text
For this:

In Hierarchy → Create → UI → Text


→ Rename it as CountText.

By doing so we will get three objects


Canvas, Text, EventSystem in which
Text is the child of Canvas

15. Select Text → Anchor → Press Shift and Alt button together and select the left top corner
50

16. Now for ending game text → Hierarchy window → Create → UI → Text.
Rename text as End Text → reset.

17. Now select player → script –> Drag and drop the CountText in Count Text option in script of
player.
And even dDrag and drop the EndText in Win Text option in script of player.

Save scenes after every successful operations.

18. Finally game is completed so let’s build the game for PC and standalone devices.
For that:

File → Build Settings → Build settings dialogue box will appear → Select the PC, MAC, Linus
Standalone option and select the scene to be build and then build and run.
51
52

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: All Scripts:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

PlayerController.cs

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float speed;


public Text countText;
public Text winText;

private Rigidbody rb;


private int count;

void Start ()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText ();
winText.text = "";
}

void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");

Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);

rb.AddForce (movement * speed);


}

void OnTriggerEnter(Collider other)


{
if (other.gameObject.CompareTag ( "Pick Up"))
{
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}

void SetCountText ()
{
53

countText.text = "Count: " + count.ToString ();


if (count >= 12)
{
winText.text = "You Win!";
}
}
}

CameraController.cs

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {

public GameObject player;

private Vector3 offset;

void Start ()
{
offset = transform.position - player.transform.position;
}

void LateUpdate ()
{
transform.position = player.transform.position + offset;
}
}

Rotator.cs

using UnityEngine;
using System.Collections;

public class Rotator : MonoBehaviour {

void Update ()
{
transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
}
}

You might also like