Final Game Programming
Final Game Programming
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
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:
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
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();
}
Output
8
Practical #4
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;
}
}
}
Output
Practical #5
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);
Output
12
Practical #6
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
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
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
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.
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
14. Now we will count the score and End the game
For this:
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.
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.
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;
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.
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
//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");
//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);
}
//... then set the other object we just collided with to inactive.
other.gameObject.SetActive(false);
//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 ();
CompleteCameraController.cs
using UnityEngine;
using System.Collections;
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
CompleteRotator.cs
using UnityEngine;
using System.Collections;
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
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.
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
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.
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
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");
Mover.cs
using UnityEngine;
using System.Collections;
void Start ()
{
rigidbody.velocity = transform.forward * speed;
}
}
DestroyByBoundary.cs
using UnityEngine;
using System.Collections;
RandomRotator.cs
using UnityEngine;
using System.Collections;
void Start ()
{
rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
}
}
DestroyByContact.cs
using UnityEngine;
using System.Collections;
void Start ()
{
GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent <GameController>();
}
if (gameController == null)
{
Debug.Log ("Cannot find 'GameController' script");
}
}
GameController.cs
using UnityEngine;
using System.Collections;
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;
}
}
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
DestroyByTime.cs
using UnityEngine;
using System.Collections;
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
Even we see grid lines in the preview, but we don’t need it. So for removing grid lines
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
10. Now we make the walls for the Player so that it does fall off from the ground
Hierarchy → 3D object → cube.
Make four walls and arrange them at the four ends of the plane background
48
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
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.
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
PlayerController.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
void Start ()
{
rb = GetComponent<Rigidbody>();
count = 0;
SetCountText ();
winText.text = "";
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
void SetCountText ()
{
53
CameraController.cs
using UnityEngine;
using System.Collections;
void Start ()
{
offset = transform.position - player.transform.position;
}
void LateUpdate ()
{
transform.position = player.transform.position + offset;
}
}
Rotator.cs
using UnityEngine;
using System.Collections;
void Update ()
{
transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
}
}