Skip to main content

GP Prac

GP

Published 22 min readMarkdown
********************************PRACTICAL 1************************************
AIM: Setup DirectX 11,Window Framework and Initialise Direct 3d device 
STEPS :
Step1:Visual Studio>Create New Project>Net Framework 2.0>Windows Form Application
Name your Project (pract1)
STEP 2:right click on project>application properties>build>Chatplatform>x86
STEP 3:Right click on the project>add>References (add all the 4 references )
CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace pract1
{
    public partial class Form1 : Form
    {
        Microsoft.DirectX.Direct3D.Device device;
        public Form1()
        {
            InitializeComponent();
            InitDevice();
        }
        private void InitDevice()
        {
            PresentParameters pp = new PresentParameters();
            pp.Windowed = true;
            pp.SwapEffect = SwapEffect.Discard;
            device = new Device(0, DeviceType.Hardware,
                this, CreateFlags.HardwareVertexProcessing, pp);
        }
        private void Render()
        {
            device.Clear(ClearFlags.Target, Color.Blue, 0, 1);
            device.Present();
        }
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Render();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
OUTPUT:

*******************************PRACTICAL 2************************************
Aim: Buffers, Shaders and HLSL (Draw a triangle using Direct3D 11)
FORM1.CS: 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using Microsoft.DirectX; 
using Microsoft.DirectX.Direct3D; 
namespace WindowsFormsApplication3 
{ 
 public partial class Form1 : Form 
 { 
 Microsoft.DirectX.Direct3D.Device device; 
 public Form1() 
 { 
 InitializeComponent(); 
 InitDevice(); 
 } 
 private void InitDevice() 
 { 
 PresentParameters pp = 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(115, 85, 0, 1.0f);  vertexes[0].Color = System.Drawing.Color.FromArgb(255, 0, 0).ToArgb();  vertexes[1].Position = new Vector4(690, 415, 0, 1.0f);  vertexes[1].Color = System.Drawing.Color.FromArgb(0, 255, 0).ToArgb();  vertexes[2].Position = new Vector4(115, 415, 0, 1.0f);  vertexes[2].Color = System.Drawing.Color.FromArgb(0, 0, 255).ToArgb(); 
device.Clear(ClearFlags.Target, Color.Orange, 0,1);  
device.BeginScene(); 
 device.VertexFormat = CustomVertex.TransformedColored.Format; 
 device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertexes);  
device.EndScene(); 
 device.Present(); 
 } 
 private void Form1_Paint(object sender, PaintEventArgs e)  { 
 Render(); 
 } 
 private void Form1_Load(object sender, EventArgs e) 
 { 
 } 
 } 
} 
OUTPUT:

****************************PRACTICAL 3****************************************
Aim: Texturing (Texture the Triangle using Direct 3D 11)
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
         Microsoft.DirectX.Direct3D.Device device;
        private Texture texture;
        private CustomVertex.PositionTextured[] vertex = new CustomVertex.PositionTextured[9];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_paint(object sender, PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target, Color.Black, 0, 1);
            device.BeginScene();
            device.SetTexture(0, texture);
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, vertex.Length / 3, vertex);
            device.EndScene();
            device.Present();

        }
        private void Form1_load(object sender, EventArgs e)
        {
            PresentParameters PP = 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 / 8, device.Viewport.Width / device.Viewport.Height, 1F, 10000F);
            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.5f, 1);
            vertex[1] = new CustomVertex.PositionTextured(new Vector3(3, 0, 0), 1f, 1);
            vertex[2] = new CustomVertex.PositionTextured(new Vector3(0, 3, 0), 0, 0.5f);
            texture = new Texture(device, new Bitmap("C:\\Users\\LAB2-PC04\\Desktop\\TYCS16\\GP\\mountains.jpg"),0,Pool.Managed);
        }

    }
}

OUTPUT:
 *********************************PRACTICAL 4**********************************
Aim: Lightning (Programmable Diffuse Lightning using Direct3D 11) 
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        Microsoft.DirectX.Direct3D.Device device;
        private CustomVertex.PositionNormalColored[] vertex = new CustomVertex.PositionNormalColored[9];

        public Form1()
        {
            InitializeComponent();
            initDevice();
        }

        private void initDevice()
        {
            PresentParameters pp = 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, 10000f);
            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, 2), new Vector3(1, 0, 1), Color.White.ToArgb());
            vertex[1] = new CustomVertex.PositionNormalColored(new Vector3(-1, -1, 2), new Vector3(-1, 0, 1), Color.White.ToArgb());
            vertex[2] = new CustomVertex.PositionNormalColored(new Vector3(1, -1, 2), new Vector3(-1, 0, 1), Color.White.ToArgb());
            device.RenderState.Lighting = true;
            device.Lights[0].Type = LightType.Directional;
            device.Lights[0].Diffuse = Color.BlanchedAlmond;
            device.Lights[0].Direction = new Vector3(-1, 0, -2);
            device.Lights[0].Enabled = true;

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            device.Clear(ClearFlags.Target, Color.Blue, 1.0f, 0);
            device.BeginScene();
            device.VertexFormat = CustomVertex.PositionColored.Format;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, vertex.Length / 3, vertex);
            device.EndScene();
            device.Present();
        }
    }
}
OUTPUT:

******************************PRACTICAL 5**************************************
AIM: Loading 2d models into DirectX 11 and rendering.
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX.Direct3D;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        Microsoft.DirectX.Direct3D.Device device;
        Texture texture;
        Microsoft.DirectX.Direct3D.Font font;
        public Form1()
        {
            InitializeComponent();
            initDevice();
            initFont();
            LoadTexture();
        }
        private void LoadTexture()
        {
            texture = TextureLoader.FromFile(device, "C:\\Users\\LAB2-PC04\\Desktop\\Desktop\\TYCS16\\GP\\diya.jpg");
        }

    private void initFont()
    {
        System.Drawing.Font f = new System.Drawing.Font("Algerian", 200f);
        font = new Microsoft.DirectX.Direct3D.Font(device, f);
    }
    private void initDevice()
    {
        PresentParameters pp = new PresentParameters();
        pp.Windowed = true;
        pp.SwapEffect = SwapEffect.Discard;
        device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp);
    }
    private void Form1_Paint(object sender,PaintEventArgs e)
    {
            Rectangle rect = new Rectangle(0, 0, 1400, 700);

        device.Clear(ClearFlags.Target, Color.BlanchedAlmond, 1.0f, 0);
        device.BeginScene();
        using (Sprite s = new Sprite(device))
        {
            s.Begin(SpriteFlags.AlphaBlend);
            s.Draw2D(texture, Rectangle.Empty, new Size(rect.Width, rect.Height), new Point(0, 0),0f,new Point(0,0),Color.Orchid);
            font.DrawText(s,"Mahika",new Point(200, 90), Color.White);
            s.End();

        }
        device.EndScene();
        device.Present();
    }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
OUTPUT:
 *********************************Practical 6********************************** 
Aim: Loading 3d models into DirectX 11 and rendering 
Save the images you’ll use for the animation in the bin->Debug folder of your web form application 

 Form1.cs using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data;
 using System.Drawing;
 using System.Text;
 using System.Windows.Forms; 
using Microsoft.DirectX.Direct3D; 
using Microsoft.DirectX; 
using System.IO; 

namespace WindowsFormsApplication6 
{ 
    public partial class Form1 : Form 
    {  
       private Device device;       
      private PresentParameters pres;        
 private Mesh mesh;         
private Material[] materials;        
     private Texture[] textures;         
public Form1() 
        { 
            InitializeComponent(); 
        }  
        public bool InitializeGraphics() 
        { 
            pres = new PresentParameters();       
      pres.Windowed = true; 
            pres.SwapEffect = SwapEffect.Discard;      
       pres.EnableAutoDepthStencil = true;       
      pres.AutoDepthStencilFormat = DepthFormat.D16;             
device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing,pres);             
device.RenderState.CullMode = Cull.None; 
            CreateMesh(@"airplane 2.x");             
return true; 
        } 

        public void CreateMesh(string path)         { 
            ExtendedMaterial[] exMaterials; 
            mesh = Mesh.FromFile(path, MeshFlags.SystemMemory, device, out exMaterials); 
            if (textures != null) 
            { 
                DisposeTextures(); 
            } 
            textures = new Texture[exMaterials.Length];      
       materials = new Material[exMaterials.Length];        
     for (int i = 0; i < exMaterials.Length; i++) 
            { 
                if (exMaterials[i].TextureFilename != null) 
                { 
                    string texturePath = Path.Combine(Path.GetDirectoryName(path), exMaterials[i].TextureFilename); 
                    textures[i] = TextureLoader.FromFile(device, texturePath); 
                } 
                materials[i] = exMaterials[i].Material3D;            
     materials[i].Ambient = materials[i].Diffuse; 
            } 
        }  
        private void DisposeTextures() 
        { 
            if (textures == null) 
            {                 return;             } 
            foreach (Texture t in textures) 
            { 
                if (t != null) 
                { 
                    t.Dispose(); 
                } 
            } 
        }  
        public void SetupMatrices() 
        { 
            float yaw = Environment.TickCount / 500.0F;  
           float pitch = Environment.TickCount / 500.0F;        
     float roll = Environment.TickCount / 500.0F; 
            device.Transform.World = Matrix.RotationYawPitchRoll(yaw, pitch, roll);             device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, -8), new Vector3(0, 0, 0), new Vector3(3, 1, 0)); 
            device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 
2.0F, 1.0F, 1.0F, 12.0F);      
   } 
        public void SetupLights() 
        { 
            device.RenderState.Lighting = true;         
    device.Lights[0].Diffuse = Color.White;       
      device.Lights[0].Specular = Color.White;       
      device.Lights[0].Type = LightType.Directional;            
 device.Lights[0].Direction = new Vector3(-1, -1, 3);          
   device.Lights[0].Enabled = true; 
            device.RenderState.Ambient = Color.FromArgb(0x00, 0x00, 0x00); 
        } 
        public void RenderMesh() 
        { 
            for (int i = 0; i < materials.Length; i++) 
            { 
                if (textures[i] != null) 
                { 
                    device.SetTexture(0, textures[i]); 
                } 
                device.Material = materials[i];              
   mesh.DrawSubset(i); 
            }         } 
        public void Render() 
        { 
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.SkyBlue, 1.0F, 
0);             
device.BeginScene(); 
            SetupMatrices(); 
            SetupLights();         
    RenderMesh();            
 device.EndScene();            
 device.Present(); 
        } 
        public void DisposeGraphics() 
        { 
            DisposeTextures();            
 device.Dispose(); 
        } 
        private void Form1_Load(object sender, EventArgs e) 
        {          } 
        private void Form1_Paint(object sender, PaintEventArgs e) 
        { 
            Render(); 
        } 

    } 
} 

**************************** Program.cs *************************************
using System; 
using System.Collections.Generic; using System.Windows.Forms; 

namespace WindowsFormsApplication6 
{ 
    static class Program 
    { 
        /// <summary> 
        /// The main entry point for the application. 
        /// </summary>         [STAThread]         static void Main() 
        { 
            Form1 app = new Form1();        
     app.Width = 800;             
app.Height = 600;             
app.InitializeGraphics();         
    app.Show();     
        while (app.Created) 
            { 
                app.Render(); 
                Application.DoEvents();           
            } 
            app.DisposeGraphics(); 
        } 
    } 
}  OUTPUT: 
  

*****************************PRACTICAL 7*************************************
AIM : Implement 2d UFO Tutorial.      
Step 1: Create a New Project. Give it a name, set its path and choose for the 2D model.   
Step 2 : Create a folder Sprite in Assets and Copy Paste the Assets which we have Downloaded.   
Step 3: Save the scene. File – New Scene – Save Scene – Save in the folder Scene – Name it as Main.   
Step 4: Select 2D Build.   
Step 5: Save the scene.       
Step 6 : Navigate to Assets – Sprite. Within this folder you will find a file named Background. Drag this Background into the hierarchy and it will create a new GameObject. Reset the transform.   
Step 7: Go to Gizmos menu and deselect the Grid View.   
Step 8: Next navigate to Assets – Sprite. Within this folder you will find a file named UFO. Drag this UFO into the hierarchy and it will create a new GameObject which act as a player.   
Step 9: Rename it as Player. Set its Sorting Layer as Player.   
Step 10 : Scale the Player values as X=0.75 and Y=0.75.   
Step 11: Highlight Background. Set its sorting layer to Background. Select on Add Sorting layer.   
Step 12 : Create a layer background and select background.   
Step 13 : Select the Main Camera. Set the projection to Orthographic and its size as 16.5. Also set its background color.   
Step 14: Select Player -> Add Component – >Physics2d .   
Step 15: Select RigidBody 2D.   
Step 16: Add Component –> Create Script –> Name the script as PlayerControl-> Select New script.   
Step 17: Select create and Add. Add code for the Player movement.   
Step 18: Next set gravity scale of the rigidbody to 0.   
Step 19: Set the speed property to 10.   
Step 20: Highlight Player GameObject. Add Component –> Circle Collider2D.   
Step 21: Set its radius to 2.15   
Step 22: Highlight Background GameObject. Add Component – >BoxCollider2D. Set size X=3.3 and offset X=14.3   
Step 23: Duplicate first component. Copy and Paste it. Set Offset X=-14.3   
Step 24: Duplicate first component. Copy and Paste it. Set Size Y=3.3 and Offset Y=14.3   
Step 25: Duplicate first component. Copy and Paste it by right click on first component select copy component.   
Step 26: Select Paste component as New.   
Step 27: Set Size Y=3.3 and Offset Y=-14.3.   
Step 28: Highlight MainCamera. Add Component – >Add a new script –> Name it CameraController.   
Step 29: Select Create and Add.   
Step 30: Complete the code then Drag and drop Player into the Player slot as a reference for the MainCamera.   
Step 31: Drag and Drop Pickup from Sprites in the Asset folder into the hierarchy.   
Step 32: Deactivate Player.   
Step 33: Highlight Pickup. Set the Sorting Layer to Pickup.   
Step 34: Add Component –> Circle Collider.   
Step 36: Set its radius as 0.94.   
Step 37: Add Component –> New Script –> Rename as Rotator. Add code to rotate the pickup Object.   
Step 38: Create a Prefab folder by selecting Create->Folder.   
Step 39: Rename it as Prefabs.   
Step 40: Drag and drop Pickups from Hierarchy into the Prefabs folder in Assets.   
Step 41: Create a new game object and name it as pickup. Select GameObject->Create Empty.   
Step 42: Reset its transforms.   
Step 43: Drag and drop pickup from prefab onto pickup game object you just created. Select the child pickup and place it wherever you wish and duplicate it and repeat for as many pickup objects you want.  
Step 44:Reactivate the Player GameObject. Edit the PlayerController to pick up the PickUp.
Step 45: Navigate to Prefab and highlight Pickup and set its tag as PickUp. Turn the sprite render on .   
Step 46: Select is trigger on for the circle collider.   
Step 47: Set the Rigibody’s Dynamic on. Select the PlayerController Script and add code to count the pickups. Go to Hierarchy and Add a UI Text Element by selecting UI->Legacy->Text.   
Step 48: Rename as CountText. Reset its Transforms.   
Step 49: Set the color of the text to red. Set the text as Count Text. Change the pivot using inspector and set position X=10 and Y=-10.   
Step 50: Drag and drop CountText onto the count slot.   
Step 51: Go to Hierarchy and Add a UI Text Element by selecting UI->Legacy->Text.   
Step 52: Reset the transform and Rename as WinText.   
Step 53: Set Y=75, font size to 25, color as red and its default text as Win Text.   
Step 54: Drag WinText component into WinText slot.   
Step 55: Play the game, the label should be able to increment the count when hit and the second label should display ‘You win!’ when all the pickups are hitted.   
Step 56: Go to File – Build Settings.   
Step 57: Drag and drop MainScene into the slot for scenes.     
Step 58: Click Build and save a build location. Finally you can Run the game.     

CameraController.cs   
using System.Collections; using System.Collections.Generic;  using UnityEngine;   

public class CameraController : MonoBehaviour   
{   
       public Transform player;   

       private Vector3 offset;   

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

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

Rotator.cs  
using UnityEngine; 
using  System.Collections; 
 using System.Collections.Generic;   

public class Rotator : MonoBehaviour   
{   

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

}   

PlayerController.cs   
using UnityEngine;  
using UnityEngine.UI; 
usingSystem.Collection;   
using System.Collections.Generic;   

public class PlayerController : MonoBehaviour   
{   

public float speed;      
 public Text countText;  
public Text winText; 
 public string pickUpTag = "PickUp";   
       Rigidbody2D rb2d;        
int pickUpsTotal;   
       int count;   

       void Start()   
       {   
              rb2d = GetComponent<Rigidbody2D>();        
          winText.text = string.Empty;   
              pickUpsTotal = GameObject.FindGameObjectsWithTag(pickUpTag).Length;     
count = 0;                 
SetCountText();   
       }   

       void FixedUpdate()   
       {   
              float moveHorizontal = Input.GetAxis("Horizontal");                
                        float moveVertical = Input.GetAxis("Vertical");                      
  var movement = new Vector2(moveHorizontal, moveVertical).normalized * speed *  Time.deltaTime;   
              rb2d.AddForce(movement);   
       }   


       void OnTriggerEnter2D(Collider2D target)   
       {                 if (target.CompareTag(pickUpTag))    
              {   
                     //target.gameObject.SetActive(false);     
                 Destroy(target.gameObject);     
count += 1;   
                     SetCountText();   
              }   
       }   

       void SetCountText()   
       {   
              countText.text = $"Count: {count}";    
            if (count >= 11)   
              {   
                     winText.text = "You win!";   
              }   
       }    
}   

 
Output   
 **********************************PRACTICAL 8********************************* 
AIM: Implement space shooter tutorial.      
STEP 1: Create a new project, give it a name and set the location where you wish to save the project and click on Create.         
STEP 2: Once the project is created import the Assets into the newly created projects Assets folder.  
STEP 3: Go to File – Save As and save the scene as Main into the Scene folder of Assets     
STEP 4: Go to File – Build Settings Select Web GL here and click on Switch Platform. (Optional as it is depricated).   
STEP 5 In the Build Settings click on Player Settings and set the Resolution to 600 x 900.   
STEP 6: Select game view and set the Aspect Ratio to 600 x 900   
STEP 7: Go to Assets – Model. Drag and drop PlayerShip (vehicle_player) into the hierarchy and rename it as Player and reset its Transforms   
STEP 8: Select the Player - Add Component in the inspector and select Rigidbody, uncheck the Gravity option here.   
STEP 9: Next Add Component – Mesh Collider. Check the Convex and isTrigger options   
STEP 10: Go to Prefabs – VFX – Engines, select enginer_player and drag and drop it as a child of Player. Adjust its size in the Gizmos if need be   
STEP 11: In the hierarchy select Main Camera and reset its Transforms. Set Rotation X=90 and Position Y=10, Z=5. Set the Projection as Orthographic and size=10. Set the Background to Black.   
STEP 12: Go to Window – Rendering – Lighting. Select Environment, select Environment  
Lighting as Color, Ambient Color as Black, Realtime Shadow Color as Black  
STEP 13: Delete Directional Lighting from the hierarchy and create a new directional light by clicking on + - Light – Directional Light. Name it as Main Light. Reset its transforms. Set Rotation X=20;  Y=-115, Intensity = 2.   
STEP 14: Select Main Light press Ctrl + D to duplicate the light rename it as Fill Light. Reset its transforms. Set Rotation X=5; Y=125, Intensity = 1. Change color to Cyan Blue where R=128 G=192 B=192 A=255   
STEP 15: Now duplicate the Fill Light and rename it as Rim Light. Reset its transforms. Set  
Rotation X=-15; Y=65, Intensity = 0.5 Change color to White   
STEP 16: Click Shift + Ctrl + N to create new game object and rename it as Lighting. Reset its transforms. Set Position Y=100. Drag and drop all three directional lights as child of Lighting    
STEP 17: Deactivate Player Object.    
STEP 18: In the hierarchy click + - 3D Objects – Quad. Rename as Background. Reset its transforms Set Rotation X=90. Remove the mesh collider component       
STEP 19: Click on Background in the Materials option select tile_nebula_green. Scale the  
Transform X=15 and Y=30 and Position Y= -10. Reactivate the player   
STEP 20: Go to Assets and create a folder named Scripts Go to Player Add Component – New Script – Rename as PlayerController.  Drag and drop it into the newly created scripts folder  
STEP 21: Add script to move the player into PlayerController. Save the script and return to unity. Set the speed=20, tilt=4,zmin=-6,xmax=6,zmin=-4 and zmax=8.   
STEP 22: Run the game to see player ship moving within the set bounds.   
STEP 23: Exit play mode. Deactivate the Player. Create a new game object using Shift + Ctrl + N and rename as Bolt. Reset its transforms   
STEP 24: In the hierarchy create a quad and rename it as VFX. Reset its transforms. Make it as a child of Bolt game object   
STEP 25: Set rotation X=90. Into the materials select fx_bolt_orange. Remove Mesh Collider from VFX   
STEP 26: To the bolt game object add Rigidbody component. Add Capsule Collider Component set Direction=Z axis, Height=0.5, Radius=0.03 and check isTrigger   
STEP 27: Add script to the Bolt game object and rename it as Mover. Drag and drop it to the scripts folder and edit the script to move the bolt. Save the script set speed=20 and test if the bolts are moving.   
STEP 28: Drag and drop Bolt from hierarchy into Assets – Prefabs   
STEP 29: Reactivate the player. Create a new game object rename it as ShotSpawn. Reset its transforms. Make it child of player and set Position Z=1.25  
STEP 30: Edit the PlayerController script add the code to fire round of shots from the playership upwards. Save the script and return to unity.  
STEP 31: Drag and drop Bolt from Prefab into Shot slot and ShotSpawn into ShotSpawn slot. Set FireRate=0.25   
STEP 32: Play the game and test   
STEP 33: Exit play mode. In the hierarchy click on + - 3D Object – Cube. Rename it as Boundary and reset its transforms. Set Position Z=5, Scale X=15 and Z=20. Check the isTrigger component of the Box Collider. Remove the Mesh Renderer and Mesh Filter components.   
STEP 34: Add a script component to Boundary and name it as DestroyByBoundary. Drag and drop it to the Scripts folder. Add the script to destroy the bolts. Save and return to unity and test.  
STEP 35: Exit Play mode and add a new game object rename it as Asteroid. Reset its transforms. Set Position Z=5. Go to Assets – Model and select prop_asteroid_01; drag and drop it as child of Asteroid game object and reset its transform  
STEP 36: To the asteroid game object add component Rigidbody and uncheck Gravity. Also add the Capsule Collider component. Set radius and height as per the component and select the isTrigger checkbox.  
STEP 37: Add a script and name it as RandomRotator. Drag and drop it to the scripts folder.  
Add the script to rotate the asteroid. Save the script and return to unity   
STEP 38: Set the tumble value in the inspector to 5. Set the Angular Drag value of the Rigidbody component as 0. Play to see the asteroid rotate.  
STEP 39: Exit play mode. Add component new script to the asteroid game object and name it as DestroyByContact. Drag and drop it to the script folder. Add the script to destroy the asteroid.   
STEP 40: Select Boundary and create a new tag and name it as Boundary. Set the tag as Boundary and play to test   
STEP 41: Exit play mode. Edit the DestroyByContact script and add code to produce vfx explosion on collision of the asteroid with the player ship. Save the code and return to unity   
STEP 42: Drag and drop explosion_asteroid from Assets - Prefabs – VFX – Explosions into the Explosion slot and explosion_player onto Player Explosion slot of DestroyByContact script. Drag and drop Asteroid game object into Prefabs and delete it from hierarchy.   
STEP 43: Add tag Player to Player game object   
STEP 44: Drag and drop Mover script from script folder into the Asteroid Game Object and set Speed=-5.  
STEP 45: Create a new game object and name it as Game Controller. Reset its transforms. Set its tag as GameController.   
STEP 46: Add a GameController script to the GameController object drag this script into the Scripts folder and edit the script. Save and return to unity.  
STEP 47: Drag and drop Asteroid from Prefabs into the Hazard slot and set spawn value of Z =16. Play to test.   
STEP 48: Exit play mode and edit the Game Controller script to spawn multiple hazards    
STEP 49: Set Hazard Count =10 , Spawn Wave= 0.5 , Start Wait =1, Wave Wait =4 and Spawn Value of X=6. Play to test.   
STEP 50: Exit play mode. Click on Assets – Script .Create a new C# script and name it DestroyByTime.   
STEP 51: Edit the script, save and return to Unity    
STEP 52: Go to Explosion in Prefab and add script Destroy ByTime to Asteroid Explosion  
Prefab Set Lifetime value=2.  Add DestroyBytime to all the explosions   
STEP 53: Drag and drop explosion_asteroid audio into explosion_asteroid Explosion in the Prefab folder.   
STEP 54: Drag and drop weapon_player audio onto the Player object in the hierarchy. Uncheck the Play On Awake option.  
STEP 55: Edit the PlayerController script to play audio when the shots are being fired. Save and return to unity, play and test   
STEP 56: Drag and drop music_background from Audio to GameController object, check Loop and set Volume=0.5      
STEP 57: In the hierarchy create a new game object reset its transforms. Click on + - UI – Text and rename it as ScoreText, change text to Score Text, position it to the top left of the screen   
STEP 58: Edit the GameController script. Save and return to unity      
STEP 59: Edit the DestroyByContact script. Save and return to unity   
STEP 60: Add Score Text text component into the Score Text slot of GameController script  
STEP 61: Set the score value in the DestroyByContact script of the Asteroid prefab to 10. Save and play to test if the score is being displayed.   
STEP 62: Add a new UI Text and name it Restart Text position it to the top right of the screen  
STEP 63: Add a new UI Text Component and name it as Game Over Text reset its text property and position it as per choice.   
STEP 64: To the GameController script add code to print game over when the player ship collides with the hazards and to indicate the player to press R if he wishes to restart the game. Save the script and return to Unity.  
STEP 65: Edit the DestroyByContact script to add reference to the gameOver method. Save and return to unity.   
STEP 66: Drag and drop Game Over and Restart Text to their respective slots in the  
GameController script. The game is completely ready to play    
STEP 67: Go to File – Build Settings. Drag and drop MainScene into the slot for scenes. Click Build and save a build location. Finally you can Play the game.  

OUTPUT:   
  ***********************************PRACTICAL 9*****************************  
AIM: Roll a Ball – Unity Game    
STEP 1: Open Unity. Create a New Project name it, save a location. Select 3D and Create    
STEP 2: Create a new scene. Go to File – Save As and save Scene. Name as Main  
STEP 3: Create a plane Hierarchy – 3D Object – Plane Rename as Ground. Reset its transforms. Turn off Grid line in Gizmos menu. Set Scale X=Z=2    

STEP 4: Create a sphere Hierarchy – 3D Object – Sphere Rename as Player. Reset its transforms. Set Position Y=0.5    

STEP 5: In the Project folder, create a new folder and name it as Material. Now click on    
Material and create a new material and name it as Background. Set Albedo: R=0, G=32,    
B=64. Drag and drop material onto the Ground (Plane)    

STEP 6: Select Directional Light. Set Rotation Y=60    

 

STEP 7: Add Rigidbody component to the Player game. Uncheck Is Kinematic    

STEP 8: Create a new folder in the Project folder and rename as Scripts.    
STEP 9: Add script component to the Player object and name it as PlayerController. Drag and drop it to the Scripts folder    

STEP 10: Edit the script to move the player. Save and return to Unity. Set Speed =10. Play to  test    

 

STEP 11: Set camera value as Position Y=10 Rotation X=45.    

STEP 12: Add a new script to the Main Camera. Name it as CameraController. Drag and drop  
it to the script folder    
STEP 13: Edit the script to move the camera relative to the player. Save and return to Unity.    


STEP 14: Drag and drop Player object to Player slot of CameraController script. Play the game to see the camera moving as the player moves    

STEP 15: Create a new gameobject and name it as Walls. Reset its transforms    


STEP 16: In the Hierarchy - + - 3D Objects – Cube. Reset its transforms and name it  
WestWall. Make it the child of Wall game object. Set Scale values as X=0.5, Y=2, Z=20.5. Set Position X=-10    


STEP 17: Duplicate West Wall using ctrl + D. Rename as EastWall and set Position X=10    


STEP 18: Duplicate EastWall using ctrl + D. Rename as NorthWall and set Position Z=10.   
Set Scale values as X=20.5, Y=2, Z=0.5    


STEP 19: Duplicate NorthWall using ctrl + D. Rename as SouthWall and set Position Z=-10.   
Play to test if the ball leaves the boundary or not    


STEP 20: Deactivate Player game object. Create a new Cube object name it as PickUps.   
Reset its Transforms. Set Position Y=0.5. Rotate X=Y=Z=45 and Scale X=Y=Z=0.5    


STEP 21: Add a Script component to the PickUps and name it as Rotator. Drag and drop it into the Scripts folder.  
STEP 22: Edit the Rotator script to rotate the pickup objects. Save and return to Unity. Play to test.  

STEP 23: In the Assets folder create a new Folder name it as Prefab. Drag and drop PickUps from hierarchy into the Prefabs folder.    


STEP 24: Create a new game object name it as PickUps. Reset its transforms and make PickUps cube from hierarchy child of PickUps gameobject. Duplicate the PickUp cubes as much as you want and position them accordingly.    


STEP 25: Create a new Material name it as PickUp and set its Albedo to a bright yellow. Add this material onto the PickUps in the Prefabs folder    

STEP 26: Reactivate the Player object. Edit the PlayerController script to collect the PickUps.  
Save and return to Unity    

STEP 27: Create a new tag called Pick Up and tag the PickUps object in the Prefabs Folder. Select isTrigger Property of the Collider on. Add a Rigidbody component to the PickUps Prefab. Check the Is Kinematic option. Play to test.    

STEP 28: Go to Hierarchy – UI – Text. Name as CountText. Position it to the top left side of the screen and set its default text to Count Text. Similarly create a WinText and position it at the center and set its default text to Win Text    


STEP 29: Edit the PlayerController script to display the count of pickups collected and display win text if all pickups are collected. Save and return to Unity    

STEP 30: Drag and Drop CountText into the Count Text text slot and WinText into the Win text text slot. Play to test.    


STEP 31: Go to File – Build Settings. Drag and drop Main Scene into the slot for scenes. Select the platform on which you wish to build the game. Click Build and save a build location. Finally, you can play the game.   

PlayerController.cs   using 
System.Collections; using  System.Collections.Generic; using  
UnityEngine;  using  
UnityEngine.UI;    

public class PlayerController : MonoBehaviour  {        
public float speed;       private Rigidbody rb;      
 public Text countText;    
  public Text winText;               private int count;    

// Start is called before the first frame update     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("PickUp")) {      

other.gameObject.SetActive (false);          count++;    
                        SetCountText();    
              }       
}    

         void SetCountText()   {    
                  countText.text = "Count: " + count.ToString();                      if (count >= 9) {    
                winText.text = "YOU WIN!";    
               }        
}       
}     
CameraController.cs  using 
System.Collections; using  
System.Collections.Generic; using   
UnityEngine;    

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 System.Collections; using  System.Collections.Generic;   using UnityEngine;    

public class Rotator : MonoBehaviour  {    
      // Update is called once per frame            
void Update() {    
            transform.Rotate(new Vector3 (15, 30, 45) * Time.deltaTime);      
    }      
}    
Output:

No comments yet. Be the first to comment.