Tycs GP Pract Journal
Tycs GP Pract Journal
Step 1:
i) Create new project, and select “Windows Forms Application”, select .NET Framework as
2.0 in Visuals C#.
ii) Right Click on properties Click on open click on build Select Platform Target and Select
x86.
Step 2: Click on View Code of Form 1.
Step 3:
Go to Solution Explorer, right click on project name, and select Add Reference. Click on
Browse and select the given .dll files which are “Microsoft.DirectX”,
“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.
Right click on "References" in Solution explorer. ►Add references ►Browse to the "DirectX
Managed Code" directory. ►Select these three files. ► Microsoft.DirectX.Direct3DX ►
Microsoft.DirectX.Direct3D.dll ► Microsoft.DirectX.dll and add.
Step 4:
Go to the Properties Section of Form, select Paint in the Event List and enter as Form1_Paint.
Step 5:
Edit the Form’s C# code file. Namespace must be the same as project name.
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 GP_P1
{
public partial class Form1 : Form
{
Microsoft.DirectX.Direct3D.Device device;
public Form1()
{
InitializeComponent();
InitDevice();
}
● Step 1: Install Python: Before installing Pygame, ensure that Python is installed on your
system. Visit the official Python website (python.org) and download the latest stable version
compatible with your operating system. Follow the installation instructions provided and
verify that Python is properly installed by running “python –version” in your terminal or
command prompt.
● Step 2: Install Pygame: To install Pygame, you need to use a package manager such as pip,
which is commonly bundled with Python installations. Run your terminal or command
prompt and execute the following command: “pip install pygame“. The command will
download and install the latest stable version of Pygame from the Python Package Index.
● Step 3: Verify the Installation: Run a simple test script to confirm that Pygame is installed
correctly. Create a new file in Python and import the Pygame module by adding the line
“import pygame”. Save the file with a “.py” extension and execute it. If no errors occur,
Pygame is successfully installed.
Part A
CODE:
import pygame
pygame.init()
# Window dimensions
height = 400
width = 400
# Resize the image to fit the window size (or any desired dimensions)
image = pygame.transform.scale(image, (width, height)) # Scaling the image
pygame.init()
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == MOUSEBUTTONDOWN:
if rect.collidepoint(event.pos):
moving = True
elif event.type == MOUSEBUTTONUP:
moving = False
elif event.type == MOUSEMOTION and moving:
rect.move_ip(event.rel)
pygame.quit()
PRACTICAL 3
Aim: Develop Snake Game using Pygame
Code:
import pygame
import time
import random
# Snake speed
snake_speed = 10
# Window size
window_x = 720
window_y = 480
# Defining colors
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# Initializing pygame
pygame.init()
# Fruit position
fruit_position = [random.randrange(1, (window_x // 10)) * 10,
random.randrange(1, (window_y // 10)) * 10]
fruit_spawn = True
# Initial score
score = 0
# If two keys are pressed simultaneously, prevent the snake from moving into
two directions at once
direction = change_to
if not fruit_spawn:
fruit_position = [random.randrange(1, (window_x // 10)) * 10,
random.randrange(1, (window_y // 10)) * 10]
fruit_spawn = True
Target.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Target : MonoBehaviour {
public GameManager gameManager;
// Use this for initialization
void Start () {
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update () {
}
private void OnMouseDown()
{
gameManager.IncrementScore();
Destroy(gameObject);
}
}
Output:
PRACTICAL 5
Aim: Create 2D Infinite Scrolling Background
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
Output:
PRACTICAL 6
Aim: Create Camera Shake Effect in Unity
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
}
}
Output:
PRACTICAL 7
Aim: Design and Animate Game character in unity.
Stages
for preparing a character (modeling, rigging, and skinning)
How to obtain humanoid models
There are three main ways to obtain humanoid models for with the Mecanim Animation system:
1. Use a procedural character system or character generator such
as Poser, Makehuman or Mixamo. Some of these systems will rig and skin your mesh (eg,
Mixamo) while others will not. Furthermore, these methods may require that you reduce the
number of polygons in your original mesh to make it suitable for use in Unity.
2. Purchase demo examples and character content from the Unity Asset Store.
3. Also, you can of course prepare your own character from scratch.
Export & Verify
Unity imports a number of different generic and native 3D file formats. The format we recommend
for exporting and verifying your model is FBX 2012 since it will allow you to:
Export the mesh with the skeleton hierarchy, normals, textures and animation
Re-import into your 3D package to verify your animated model has exported as you expected
Export animations without meshes
Preparing your own character
There are three main steps in creating an animated humanoid character from
scratch: modelling, rigging and skinning.
Modelling
This is the process of creating your own humanoid mesh in a 3D modelling package - 3DSMax,
Maya, Blender, etc. Although this is a whole subject in its own right, there are a few guidelines you
can follow to ensure a model works well with animation in a Unity project.
Observe a sensible topology. The exact nature of a “sensible” structure for your mesh is
rather subtle but generally, you should bear in mind how the vertices and triangles of the
model will be distorted as it is animated. A poor topology will not allow the model to move
without unsightly distortion of the mesh. A lot can be learned by studying existing 3D
character meshes to see how the topology is arranged and why.
Be mindful of the scale of your mesh. Do a test import and compare the size of your imported
model with a “meter cube” (the standard Unity cube primitive has a side length of one unit, so
it can be taken as a 1m cube for most purposes). Check the units your 3D package is using
and adjust the export settings so that the size of the model is in correct proportion to the cube.
Unless you are careful, it is easy to create models without any notion of their scale and
consequently end up with a set of objects that are disproportionate in size when they are
imported into Unity.
Arrange the mesh so that the character’s feet are standing on the local origin or “anchor
point” of the model. Since a character typically walks upright on a floor, it is much easier to
handle if its anchor point (ie, its transform position) is directly on that floor.
Model in a T-pose if you can. This will help allow space to refine polygon detail where you
need it (e.g. underarms). This will also make it easier to position your rig inside the mesh.
Clean up your model. Where possible, cap holes, weld verts and remove hidden faces, this
will help with skinning, especially automated skinning processes.
You will see a list available clips which you can preview by pressing Play in the Preview
Window (lower down in the inspector). The frame ranges of the clips can be edited, if needed.
Working with models that have unsplit animations
For models where the clips are supplied as one continuous animation, the Animation tab in
the Animation Importer Inspector will look like this:
In cases like this, you can define the frame ranges that correspond to each of the separate animation
sequences (walking, jumping, etc). You can create a new animation clip by pressing (+) and selecting
the range of frames that are included in it.
For example:
walk animation during frames 1 - 33
run animation during frames 41 - 57
kick animation during frames 81 - 97
The Import Settings Options for Animation
In the Import Settings, the Split Animations table is where you tell Unity which frames in your asset
file make up which Animation Clip. The names you specify here are used to activate them in your
game.
For further information about the animation inspector, see the Animation Clip component reference
page.
Animating objects and properties in Unity using Mecanim
You can create animation clips which animate any object or component property using Unity’s
animation window. These animation clips can then be arranged into a state machine in exactly the
same way as external animation clips such as character animations. For example, you could animate
the motion of a camera, the colour of a light, the individual frames of a sprite animation, or a public
property of a script.
To set up a Character or other GameObject for animation, you need to follow this process:
Create a New Animator Controller
Open the Animator Window to edit the Animator Controller
Drag the desired animation clip into the Animator Controller Window
Drag the model asset into the Hierarchy.
Add the animator controller to the Animator component of the asset.
Importing Animations using multiple model files
Another way to import animations is to follow a naming scheme that Unity allows for the animation
files. You create separate model files and name them with the convention
‘modelName@animationName.fbx’. For example, for a model called “goober”, you could import
separate idle, walk, jump and walljump animations using files named “goober@idle.fbx”,
“goober@walk.fbx”, “goober@jump.fbx” and “goober@walljump.fbx”. Only the animation data
from these files will be used, even if the original files are exported with mesh data.
The
Mask Definition, Humanoid and Transform options
Definition
Allows you to specify whether you want to create a one-off mask in the inspector specially for this
clip, or whether you want to use an existing mask asset from your project.
If you want to create a one-off mask just for this clip, choose / Create From This Model /.
If you are going to set up multiple clips with the same mask, you should select / Copy From Other
Mask / and use a mask asset. This allows you to re-use a single mask definition for many clips.
When Copy From Other Mask is selected, the Humanoid and Transform options are unavailable,
since these relate to creating a one-off mask within the inspector for this clip.
Here,
the Copy From Other option is selected, and a Mask asset has been assigned
Humanoid
The Humanoid option gives you a quick way of defining a mask by selecting or deselecting the body
parts of a human diagram. These can be used if the animation has been marked as humanoid and has a
valid avatar.
The
Humanoid mask selection option
Transform
This option allows you to specify a mask based on the individual bones or moving parts of the
animation. This gives you finer control over the exact mask definition, and also allows you to apply
masks to non-humanoid animation clips.
The Humanoid mask selection option
Animation Curves on Imported Clips
Animation curves can be attached to imported animation clips in the Animations tab of
the Animation Import Settings.
These curves allow you to add additional animated data to an imported clip, which can allow you to
animate the timings of other items based on the the state of an animator. For example, in a game set in
icy conditions, an extra animation curve could be used to control the emission rate of a particle system
to show the player’s condensing breath in the cold air.
To add a curve to an imported animation, first select the imported animation file in your project view,
then in the import settings in the inspector, select the Animations button.
View the Animations section of the
Import Settings for your animation file
Then scroll all the way to the bottom of the inspector to find the Curves heading, among the four fold-
out headings as shown:
Steps:
1. Import Assest
2. Right Click-> Create Empty ->Rename: GameObject
Start by double clicking on Unity to launch it. Even the longest journey starts with a single step.
Now create a new project and make sure you choose ‘2D’. Once you’re in, you’ll be greeted with a
few different windows. These do stuff. We don’t have time to explain, so just follow my directions
and you’ll pick it up as we go.
The first thing you’ll want to do is to create a sprite to be your character. The easiest way to do that is
to draw a square. We’re going to give it a couple of eyes. If you want to be even faster still, you can
just grab a sprite you like from somewhere.
Save this sprite and then just drag and drop it into your ‘scene’ by placing it in the biggest window.
You’ll notice that it also pops up on the left in the ‘hierarchy’.
Advertisement
Now we want to create some platforms. Again, we’re going to make do with a simple square and
we’ll be able to resize this freehand to make walls, platforms and what have you.
There we go, beautiful. Drop it in the same way you just did.
We already have something that looks like a ‘game’. Click play and you should see a static scene for
now.
We can change that by clicking on our player sprite and looking over to the right to the window called
the ‘inspector’. This is where we change properties for our GameObjects.
Choose ‘Add Component’ and then choose ‘Physics 2D > RigidBody2D’. You’ve just added physics
to your player! This would be incredibly difficult for us to do on our own and really highlights the
usefulness of Unity.
We also want to fix our orientation to prevent the character spinning and freewheeling around. Find
‘constraints’ in the inspector with the player selected and tick the box to freeze rotation Z. Now click
play again and you should find your player now drops from the sky to his infinite doom.
Take a moment to reflect on just how easy this was: simply by applying this script called
‘RigidBody2D’ we have fully functional physics. Were we to apply the same script to a round shape,
it would also roll and even bounce. Imagine coding that yourself and how involved that would be!
To stop our character falling through the floor, you’ll need to add a collider. This is basically the solid
outline of a shape. To apply that, choose your player, click ‘Add Component’ and this time select
‘Physics 2D > BoxCollider2D’.
Take a moment to reflect on just how easy this was: simply by applying this script called
‘RigidBody2D’ we have fully functional physics.
Do the precise same thing with the platform, click play and then your character should drop onto the
solid ground. Easy!
One more thing: to make sure that the camera follows our player whether they’re falling or moving,
we want to drag the camera object that’s in the scene (this was created when you started the new
project) on top of the player. Now in the hierarchy (the list of GameObjects on the left) you’re going
to drag the camera so that it is indented underneath the player. The camera is now a ‘child’ of the
Player GameObject, meaning that when the player moves, so too will the camera.
Your first script
We’re going to make a basic infinite runner and that means our character should move right across the
screen until they hit an obstacle. For that, we need a script. So right click in the Assets folder down
the bottom and create a new folder called ‘Scripts’. Now right click again and choose ‘Create > C#
Script’. Call it ‘PlayerControls’.
For the most part the scripts we create will define specific behaviors for our GameObjects.
Now double click on your new script and it will open up in Visual Studio if you set everything up
correctly.
There’s already some code here, which is ‘boiler plate code’. That means that it’s code that you will
need to use in nearly every script, so its ready-populated for you to save time. Now we’ll add a new
object with this line above void Start():
Code
public Rigidbody2D rb;
Then place this next line of code within the Start() method to find the rigidbody. This basically tells
Unity to locate the physics attached to the GameObject that this script will be associated with (our
player of course). Start() is a method that is executed as soon as a new object or script is created.
Locate the physics object:
Code
rb = GetComponent<Rigidbody2D>();
Add this inside Update():
Code
rb.velocity = new Vector2(3, rb.velocity.y);
Update() refreshes repeatedly and so any code in here will run over and over again until the object is
destroyed. This all says that we want our rigidbody to have a new vector with the same speed on the y
axis (rb.velocity.y) but with the speed of ‘3’ on the horizontal axis. As you progress, you’ll probably
use ‘FixedUpdate()’ in future.
Save that and go back to Unity. Click your player character and then in the inspector select Add
Component > Scripts and then your new script. Click play, and boom! Your character should now
move towards the edge of the ledge like a lemming.
Note: If any of this sounds confusing, just watch the video to see it all being done – it’ll help!
Very basic player input
If we want to add a jump feature, we can do this very simply with just one additional bit of code:
Code
Copy Text
if (Input.GetMouseButtonDown(0)) {
rb.velocity = new Vector2(rb.velocity.x, 5);
}
This goes inside the Update method and it says that ‘if the player clicks’ then add velocity on the y
axis (with the value 5). When we use if, anything that follows inside the brackets is used as a kind of
true or false test. If the logic inside said brackets is true, then the code in the following curly brackets
will run. In this case, if the player clicks the mouse, the velocity is added.
Android reads the left mouse click as tapping anywhere on the screen! So now your game has basic
tap controls.
Finding your footing
This is basically enough to make a Flappy Birds clone. Throw in some obstacles and learn how to
destroy the player when it touches them. Add a score on top of that.
If you get this down, no challenge will be too great in future
But we have a little more time so we can get more ambitious and make an infinite runner type game
instead. The only thing wrong with what we have at the moment is that tapping jump will jump even
when the player isn’t touching the floor, so it can essentially fly.
Add the following code to your script above the Update() method:
Code
public Transform groundCheck;
public Transform startPosition;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
Add this line to the Update method above the if statement:
Code
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
Finally, change the following line so that it includes && onGround:
Code
Copy Text
if (Input.GetMouseButtonDown(0) && onGround) {
The entire thing should look like this:
Code
Copy Text
public class PlayerControls : MonoBehaviour
{
public Rigidbody2D rb;
public Transform groundCheck;
public Transform startPosition;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool onGround;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
rb.velocity = new Vector2(3, rb.velocity.y);
onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius,
whatIsGround);
if (Input.GetMouseButtonDown(0) && onGround) {
rb.velocity = new Vector2(rb.velocity.x, 5);
}
}
What we’re doing here is creating a new transform – a position in space – then we’re setting its radius
and asking if it is overlapping a layer called ground. We’re then changing the value of the Boolean
(which can be true or false) depending on whether or not that’s the case.
So, onGround is true if the transform called groundCheck is overlapping the layer ground.
If you click save and then head back to Unity, you should now see that you have more options
available in your inspector when you select the player. These public variables can be seen from within
Unity itself and that means that we can set them however we like.
Right-click in the hierarchy over on the left to create a new empty object and then drag it so that it’s
just underneath the player in the Scene window where you want to detect the floor. Rename the object
‘Check Ground’ and then make it a child of the player just as you did with the camera. Now it should
follow the player, checking the floor underneath as it does.
Select the player again and, in the inspector, drag the new Check Ground object into the space where
it says ‘groundCheck’. The ‘transform’ (position) is now going to be equal to the position of the new
object. While you’re here, enter 0.1 where it says radius.
Finally, we need to define our ‘ground’ layer. To do this, select the terrain you created earlier, then up
in the top right in the inspector, find where it says ‘Layer: Default’. Click this drop down box and
choose ‘Add Layer’.
Now click back and this time select ‘ground’ as the layer for your platform (repeat this for any other
platforms you have floating around). Finally, where it says ‘What is Ground’ on your player, select
the ground layer as well.
You’re now telling your player script to check if the small point on the screen is overlapping anything
matching that layer. Thanks to that line we added earlier, the character will now only jump when that
is the case.
And with that, if you hit play, you can enjoy a pretty basic game requiring you to click to jump at the
right time.
With that, if you hit play you can enjoy a pretty basic game requiring you to click to jump at the right
time. If you set your Unity up properly with the Android SDK, then you should be able to build and
run this and then play on your smartphone by tapping the screen to jump.
The road ahead
Obviously there’s a lot more to add to make this a full game. The player should to be able to die and
respawn. We’d want to add extra levels and more.
PRACTICAL 10
Aim: Create Intelligent Enemies In Unity
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
switch (enemyState)
{
case AISTATE.PATROL:
StartCoroutine(PatrolState());
break;
case AISTATE.CHASE:
StartCoroutine(ChaseState());
break;
case AISTATE.ATTACK:
StartCoroutine(AttackState());
break;
}
}
}
public IEnumerator AttackState()
{
while (enemyState == AISTATE.ATTACK)
{
if (Vector3.Distance(transform.position, player.position) > DistanceOffset)
{
ChangeState(AISTATE.CHASE);
yield break;
}
print("Attack");
enemy.SetDestination(player.position);
yield return null;
}
yield break;
}
public IEnumerator PatrolState()
{
while (enemyState == AISTATE.PATROL)
{
enemy.SetDestination(currentWaypoint.position);
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
ChangeState(AISTATE.CHASE);
}
}
}