Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Game Programming

game programing project

Uploaded by

sawantsiddesh45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Game Programming

game programing project

Uploaded by

sawantsiddesh45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

INDEX

SR. DATE TITLE PG.NO TEACHERS


NO SIGN

1 26\06\2024 Setup DirectX 11, Window Framework and 2


Initialize Direct3D Device. Loading Models
into DirectX 11 and rendering.
2 31\07\2024 Learn Basic Game Designing Techniques 4
With pygame
3 10\07\2024 Develop Snake Game Using pygame. 9

4 24\07\2024 Create 2D Target Shooting Game. 13

5 07\08\2024 Creating 2D Infinite Scrolling Background. 19

6 14\08\2024 Create Camera Shake Effect in Unity. 20

7 21\08\2024 Design and Animate Game Character in 22


Unity.

8 04\09\2024 Create Snowfall Particle effect in Unity. 24

9 25\09\2024 Develop Android Game With Unity. 25

10 09\10\2024 Create Intelligent enemies in Unity. 32

1
Practical No:-1

AIM:- Setup DirectX 11, Window Framework and Initialize Direct3D Device. Loading
Models into DirectX 11 and rendering.
In this practical we are just learning the window framework and initializing a Direct3D device.
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”.
Step 4:- Go to 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 as same as your project name.
Loading models into DirectX 11 and rendering

Input:-
using Microsoft.DirectX.Direct3D;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Game3D
{
public partial class Form1 : Form
{

Microsoft.DirectX.Direct3D.Device device;
public Form1()
{
InitializeComponent();
InitDevice();
}

2
public void InitDevice()
{
PresentParameters pp = new PresentParameters();
pp.Windowed = true; // correct property name
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp); // use the correct variable and pass
presentParameters
}
public void Render() // method name should start with a capital letter
{
device.Clear(ClearFlags.Target, Color.CornflowerBlue, 0, 1); // correct order of
parameters
device.Present(); // use the correct variable
}
private void Form1_Paint_1(object sender, PaintEventArgs e)
{
Render();
}
}
}

Output:-

3
Practical No:-2
AIM:- Learn Basic Game Designing Techniques With Pygame.
A) Simple pygame Example
Input:-
import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done=False
while not done:
for event in pygame.event.get():
if event.type==pygame.QUIT:
done=True
pygame.display.flip()
Output:-

B) Pygame Adding Image.


Input:-
import pygame
pygame.init()
white = (255, 255, 255)
height = 400
width = 400
display_surface = pygame.display.set_mode((height, width))
pygame.display.set_caption('Image')
4
image = pygame.image.load('C:/Users/AV/PycharmProjects/practical2/assets/download.jfif')
while True:
display_surface.fill(white)
display_surface.blit(image, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()
Output:-

C) Pygame Rect.
Input:-
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.draw.rect(screen, (0, 125, 255), pygame.Rect(30, 30, 60, 60))

pygame.display.flip()

5
Output:-

D) Pygame Keydown
Input:-
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
is_blue = True
x = 30
y = 30
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue

6
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]: y -= 2
if pressed[pygame.K_DOWN]: y += 2
if pressed[pygame.K_LEFT]: x -= 2
if pressed[pygame.K_RIGHT]: x += 2
if is_blue:
color = (0, 128, 255)
else:
color = (255, 100, 0)
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
Output:-

7
E) Pygame Text and Font.
Input:-
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
done = False
font = pygame.font.SysFont("Times new Roman", 72)
text = font.render("Hello, Pygame", True, (158, 16, 16))
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
screen.fill((255, 255, 255))
screen.blit(text,(320 - text.get_width() // 2, 240 - text.get_height() // 2))
pygame.display.flip()

Output:-

8
Practical no.3
AIM:- Develop Snake Game using pygame.
Input:-
import pygame
import time
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Load background image and iconC:\Users\admin\PycharmProjects
background =
pygame.image.load("C:/Users/admin/PycharmProjects/pythonProject/assets/background.png"
)
background = pygame.transform.scale(background, (WIDTH, HEIGHT))
icon =
pygame.image.load("C:/Users/admin/PycharmProjects/pythonProject/assets/snake.png")
# Set the game window's icon
pygame.display.set_icon(icon)
# Initialize the window
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")

9
# Snake initial position and speed
snake = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
snake_direction = (0, -1)
snake_speed = 10
# Food initial position
food = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
# Score
score = 0

# Game over flag


game_over = False
# Main game loop
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != (0, 1):
snake_direction = (0, -1)
elif event.key == pygame.K_DOWN and snake_direction != (0, -1):
snake_direction = (0, 1)
elif event.key == pygame.K_LEFT and snake_direction != (1, 0):
snake_direction = (-1, 0)
elif event.key == pygame.K_RIGHT and snake_direction != (-1, 0):
snake_direction = (1, 0)
# Move the snake
x, y = snake[0]
new_head = (x + snake_direction[0], y + snake_direction[1])
# Check for collision with food
if new_head == food:

10
score += 1
food = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
else:
snake.pop()
# Check for collision with walls or itself
if (
new_head[0] < 0
or new_head[0] >= GRID_WIDTH
or new_head[1] < 0
or new_head[1] >= GRID_HEIGHT
or new_head in snake
):
game_over = True
snake.insert(0, new_head)
# Draw the background image
window.blit(background, (0, 0))
# Draw everything else (snake, food, score, etc.)
for segment in snake:
pygame.draw.rect(
window, GREEN, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE,
GRID_SIZE, GRID_SIZE)
)
pygame.draw.rect(
window, RED, (food[0] * GRID_SIZE, food[1] * GRID_SIZE, GRID_SIZE,
GRID_SIZE)
)
# Display the score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, WHITE)
window.blit(score_text, (10, 10))
pygame.display.update()

11
# Control game speed
pygame.time.Clock().tick(snake_speed)
# Game over message
font = pygame.font.Font(None, 72)
game_over_text = font.render("Game Over", True, WHITE)
game_over_rect = game_over_text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
window.blit(game_over_text, game_over_rect)
pygame.display.update()
# Wait for a few seconds before exiting
time.sleep(2)
# Quit Pygame
pygame.quit(

Output:-

12
Practical No:-4
AIM:- Create 2D Target Shooting Game.
Input:-
import pygame
import sys
import random
from math import *
pygame.init()
width = 500
height = 50
display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Balloon Shooter")
clock = pygame.time.Clock()
margin = 100
lowerBound = 100
score = 0
# Colors
white = (230, 230, 230)
lightBlue = (174, 214, 241)
red = (231, 76, 60)
lightGreen = (25, 111, 61)
darkGray = (40, 55, 71)
darkBlue = (21, 67, 96)
green = (35, 155, 86)
yellow = (244, 208, 63)
blue = (46, 134, 193)
purple = (155, 89, 182)
orange = (243, 156, 18)
font = pygame.font.SysFont("Snap ITC", 25)
# Balloon Class

13
class Balloon:
def init (self, speed):
self.a = random.randint(30, 40)
self.b = self.a + random.randint(0, 10)
self.x = random.randrange(margin, width - self.a - margin)
self.y = height - lowerBound
self.angle = 90
self.speed = -speed
self.probPool = [-1, -1, -1, 0, 0, 0, 0, 1, 1, 1]
self.length = random.randint(50, 100)
self.color = random.choice([red, green, purple, orange, yellow, blue])
# Move balloon around the Screen
def move(self):
direct = random.choice(self.probPool)
if direct == -1:
self.angle += -10
elif direct == 0:
self.angle += 0
else:
self.angle += 10
self.y += self.speed * sin(radians(self.angle))
self.x += self.speed * cos(radians(self.angle))
if (self.x + self.a > width) or (self.x < 0):
if self.y > height / 5:
self.x -= self.speed * cos(radians(self.angle))
else:
self.reset()
if self.y + self.b < 0 or self.y > height + 30:
self.reset()
# Show/Draw the balloon

14
def show(self):
pygame.draw.line(display, darkBlue, (self.x + self.a / 2, self.y + self.b),
(self.x + self.a / 2, self.y + self.b + self.length))
pygame.draw.ellipse(display, self.color, (self.x, self.y, self.a, self.b))
pygame.draw.ellipse(display, self.color, (self.x + self.a / 2 - 5, self.y + self.b - 3, 10, 10))
# Check if Balloon is bursted
def burst(self):
global score
pos = pygame.mouse.get_pos()
if onBalloon(self.x, self.y, self.a, self.b, pos):
score += 1
self.reset()
# Reset the Balloon
def reset(self):
self.a = random.randint(30, 40)
self.b = self.a + random.randint(0, 10)
self.x = random.randrange(margin, width - self.a - margin)
self.y = height - lowerBound
self.angle = 90
self.speed -= 0.002
self.probPool = [-1, -1, -1, 0, 0, 0, 0, 1, 1, 1]
self.length = random.randint(50, 100)
self.color = random.choice([red, green, purple, orange, yellow, blue])
balloons = []
noBalloon = 10
for i in range(noBalloon):
obj = Balloon(random.choice([1, 1, 2, 2, 2, 2, 3, 3, 3, 4]))
balloons.append(obj)
def onBalloon(x, y, a, b, pos):
if (x < pos[0] < x + a) and (y < pos[1] < y + b):

15
return True
else:
return False
# show the location of Mouse
def pointer():
pos = pygame.mouse.get_pos()
r = 25
l = 20
color = lightGreen
for i in range(noBalloon):
if onBalloon(balloons[i].x, balloons[i].y, balloons[i].a, balloons[i].b, pos):
color = red
pygame.draw.ellipse(display, color, (pos[0] - r / 2, pos[1] - r / 2, r, r), 4)
pygame.draw.line(display, color, (pos[0], pos[1] - l / 2), (pos[0], pos[1] - l), 4)
pygame.draw.line(display, color, (pos[0] + l / 2, pos[1]), (pos[0] + l, pos[1]), 4)
pygame.draw.line(display, color, (pos[0], pos[1] + l / 2), (pos[0], pos[1] + l), 4)
pygame.draw.line(display, color, (pos[0] - l / 2, pos[1]), (pos[0] - l, pos[1]), 4)
def lowerPlatform():
pygame.draw.rect(display, darkGray, (0, height - lowerBound, width, lowerBound))
def showScore():
scoreText = font.render("Balloons Bursted : " + str(score), True, white)
display.blit(scoreText, (150, height - lowerBound + 50))
def close():
pygame.quit()
sys.exit()
def game():
global score
loop = True
while loop:
for event in pygame.event.get():

16
if event.type == pygame.QUIT:
close()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
close()
if event.key == pygame.K_r:
score = 0
game()
if event.type == pygame.MOUSEBUTTONDOWN:
for i in range(noBalloon):
balloons[i].burst()
display.fill(lightBlue)
for i in range(noBalloon):
balloons[i].show()
pointer()

for i in range(noBalloon):
balloons[i].move()
lowerPlatform()
showScore()
pygame.display.update()
clock.tick(60)
game()

17
Output:-

18
Practical No:- 5
AIM:- Creating 2D Infinite Scrolling Background.
Step 1:- Open unity software an create a new project Select 2D Object.
Step 2:- Setting up the filled

 Download the Long Image


 Go to Assets add the Image And set the image
Step 3:- Add C# Script change the name of the C# Script add the code shown below:
Input:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bgScroller : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
transform.position += new Vector3(-5 * Time.deltaTime, 0);

if (transform.position.x < -21.5)


{
transform.position = new Vector3(21.5f, transform.position.y);
}
}
}
Step 4:- Setting up the Image create Duplicate Image and set
Step 5:- Click on the Play button see the Screen Scrolling Background
Output:-

19
Practical No:- 6
AIM:- Create Camera Shake Effect in Unity.
Step 1:- Create New Project Add Project Name Camera Shake Take 3D Object.
Step 2:- Go to + click 3D object select a random shape.
Step 3:- Add C# Script change the name of the C# Script add the code shown below:
Input:-
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
// Transform of the camera to shake. Grabs the gameObject's transform
// if null.
public Transform camTransform;
// How long the object should shake for.
public float shakeDuration = 0f;
// Amplitude of the shake. A larger value shakes the camera harder.
public float shakeAmount = 0.7f;
public float decreaseFactor = 1.0f;
Vector3 originalPos;
void Awake()
{
if (camTransform == null)
{
camTransform = GetComponent(typeof(Transform)) as Transform;
}
}
void OnEnable()
{
originalPos = camTransform.localPosition;
}
void Update()
{
if (shakeDuration > 0)
{
camTransform.localPosition = originalPos + Random.insideUnitSphere *
shakeAmount;

shakeDuration -= Time.deltaTime * decreaseFactor;


}
else
{
shakeDuration = 0f;
camTransform.localPosition = originalPos;
}
}
}

20
Step 4:- Set Shake Duration and Then play see screen

Output:-

21
Practical No:- 7
AIM:- Design and animate game character in unity
Input:-
Step 1:- go to google and login in to maximo and select your character

Step 2:-
Download the character and select the format as FBX for unity(.fbx)

Step 3 :- select the animation and download it select skin as without skin.

Step 4:- Goto unity hub and create a new project and select 3D object and give a project
name.

22
Step 5 :- Add Plane to SampleScene
Step 6:- Drag and drop the character and animation in the assets folder
Step 7:- Drag and drop the character in the plane
Step 8:- (i) click on the folder of character and goto the rig and change the Animation type to
humanoid and click on apply
(ii) create a folder in the assets folder and named as Material and then extract textures
and materials in the materials folder
Step 9:- (i) click on the animation folder and goto rig and change the animation type to the
humanoid and change the Avatar definition to Copy from other avatar and then change the
source
(ii) click on animation and tick the loop time
Step 10:- In Assets folder create the animator controller and change its name
Step 11:- then open animator controller and then drag and drop the animation

Step 12:- run the file

Output :-

23
Practical No:- 8
Aim:- Create Snowfall Particle effect in Unity.
Step 1:- Create a New Particle System:
• In the Unity Editor, select the Game Object where you want to add the snowfall effect.
Step 2:- Configure the Particle System:
• In the Inspector window, you'll see the Particle System component's settings. Adjust these
settings to create a snowfall effect:
• Duration: Set this to a value that suits the length of your snowfall scene. For an ongoing
snowfall, you can set it to a high value or loop the system.
• Start Lifetime: This determines how long each snowflake particle will stay on screen. Set
it to a value that makes the snowflakes fall for an appropriate amount of time (e.g., 5
seconds).
• Start Speed: Adjust the initial speed of the snowflakes. Typically, a small value like 1-5
units per second will work.
• Start Size: Set the size of the snowflakes. They should be small, like 0.05 to 0.2.
• Start Color: Choose a light blue or white color to resemble snow.
• Emission: Configure the rate at which particles are emitted. Set the rate to create a dense
snowfall. For example, you might try starting with 100 particles per second.
• Shape: Choose "Cone" as the shape and adjust the angle and radius to control the area
where snowflakes will spawn.
• Gravity Modifier: Apply a downward force (negative value) to simulate gravity. Use a
small negative value, like -0.1, to make snowflakes fall gently
Step 3:- Press the Play button in Unity to see your snowfall effect in action.
Output:-

24
Practical No:- 9
Aim :- Develop Android game with Unity.
Input:-
Step1 :- Open Unity Hub & create a new 3D Project & Give it name.
Step2:- After that go to file option & go to ‘build settings’ & choose Android and switch
platform(If it is not showing switch platform download the Android Platform).
Step3:- Goto Scene  change the SampleScene name to Game.
Step4:- Goto Game Display and change Free Aspect to 16:9 Portrait.
Step5:- Select Main Camera  change the ‘Clear flags’ option to ‘Solid Color’ and change
the background Color.
Step6:- In Assets folder create a three new folder named as ‘Materials’, ’Scripts’ & ‘Prefab’.
Step7:- In Hierarchy Create a three 3D Object Cube and name them ‘Ground’, ‘Player’ &
‘Obstacle’.
Step8 :- In Material folder right clickCreateMaterial and change the name to’Mat1’ and
then duplicate item 3 times. For duplicate press (ctrl + d).
Step 9:- Select Mat1, then its color by going to albedo option. Repeat the process for the
other materials. Then drag and drop the Mat1 to the Ground.
Step10:- Select the Ground and change its Scale Z axis to 200. Then change the tag option to
Ground which was firstly Untagged.
Step11:- Select Player and change its position of Y axis to 1. Then drag and drop Mat2 to
Player. Go to tag and change Untagged Player.
Step12:- Change the Camera Position as per your need.
Step13:- Select Obstacle and change its position of Y & Z axis (Y=0.5). Change the scale of
X axis. Change tag option Untagged Obstacle. Drag and drop Mat3 to Obstacle.
Step14:- In Scripts folder right clickCreateC# Scripts. Do it two more times. Changes
their names as ‘PlayerController’, ‘Obstacle’ & ‘GameManager’.
Step15:- Select Player and then drag and drop the PlayerController to Player’s Add
Component.
Step16:- In PlayerAdd component PhysicsRigidbody. Change Angular Drag to 0.
From Constraint Tick every other thing other than Y axis of Freeze Position.
Step17:- Open PlayerController and Write Code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

25
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
Rigidbody rb;
public float jumpForce;
bool canJump;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0) && canJump)
{
//jump
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
canJump = true;
}
}

26
private void OnCollisionExit(Collision collision)
{
if(collision.gameObject.tag == "Ground")
{
canJump = false;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Obstacle")
{
SceneManager.LoadScene("Game");
}
}
}
Step18:- Select Player and change the JumpForce which is in PlayerController Section to 18
unit.
Step19:- Go to EditProject SettingsPhysicsGravity Y axis = -50.
Step20:- Select Obstacle go to the box collider tick ‘Is trigger’.
Step21:- Drag and drop the Obstacle Script file into Obstacle’s add component. And then
open the script file and write the below code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public float speed;
void Start()
{
}
void Update()

27
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
private void OnBecameInvisible()
{
Destroy(gameObject);
}
}
Step22:- Drag and drop obstacle in the Prefab folder.
Step23:- In hierarchy create create empty and named as ‘ GameManager’ and then drag
and drop GameManager Script in it. Open the GameManager Script and write the below
code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
public GameObject Obstacle;
public Transform spawmPoint;
int score = 0;
public GameObject playButton;
public TextMeshProUGUI scoreText;
public GameObject player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{

28
}
IEnumerator SpawnObstacles()
{
while (true)
{
float waitTime = Random.Range(0.5f, 2f);
yield return new WaitForSeconds(waitTime);
Instantiate(Obstacle, spawmPoint.position, Quaternion.identity);
}
}
void ScoreUp()
{
score++;
scoreText.text = score.ToString();
}
public void GameStart()
{
player.SetActive(true);
playButton.SetActive(false);
StartCoroutine("SpawnObstacles");
InvokeRepeating("ScoreUp", 2f, 1f);
}
}
Step24:- Select the GameManager and give the Obstacle from the Prefab folder.
Step25:- In hierarchy select obstacle and disable it and same goes to the Player.
Step26:- In hierarchy create empty object and name it as SpawnPoint and positioned it same
as Obstacle. Then select the GameManager and drag and drop SpawnPoint into it.
Step27:- In hierarchy create canvas(+UICanvas). In Canvas, change the UI Scale Mode
to Scale with Screen Size. Reference solution (X=1920, Y=1080). Match = 0.5.
Step28:- Select Canvas right clickUIText-TextMeshPro. Import TextMeshPro Essentials.
Step29:- Goto Scene display and select 2D Mode.

29
Step30:- Rename Text-TMP to ScoreText. Text Input = 0. Positioned the ScoreText on the
Top. Change the font Size to 300. Aligned in the Centre.
Step31:- CanvasUIButton-TextMeshPro. Rename to PlayButton. In PlayButton delete
the Text(TMP).
Step32:- Download the Play Button Image from Online Browser and then import that image
in to the Assets folder. And then change its Texture type to Sprite(2D and UI) then click on
apply.
Step33:- Then select PlayButton, drag and drop PlayButton Image into the PlayButton’s
Source Image. And then Click on Set Native Size. Positioned it.
Step34:- Select PlayButton Below Button Section Onclick() press(+) then drag and drop
GameManager GameStart function.
Step35:- Add all the reference that the GameManager is needed when we select
GameManager.
Step36:- Goto FileBuild settings and make sure the platform is Android. Goto Player
Setting the Default Orientation to Portrait. Exit Player Setting.
Step37:- Then Click on Build. Create New Folders as Builds and then Name the file and
Save it there.
Input Images:-

30
OUTPUT:-

31
Practical No:- 10
Aim:- Create Intelligent Enemies in Unity.
Step 1:- Goto unity hub and create a new project and select 3D object and give a project
name.
Step 2:- Create a empty game object to sample scene and name it 'Map'.
Step 3:- Right-click to Map and then add Plane.
Step 4:- Add a few Cubes inside the Map object, Scale them to create a basic Map.
Step 5:- Create another Empty Game Object and name it "Enemy".
Step 6:- Right-click to Enemy and then add a Caplsule name "Enemy Capsule".
Step 7:- If NavMeshAgent is not available, Click on Window >> Package Manager >>
Packages: Unit Registry >> Download AI Navigation and Import it
Step 8:- Add NavMeshAgent component to our Enemy Object.
Step 9:- Create another Empty Game Object and name it "Player".
Step 10:- Right-click to Enemy and then add a Caplsule name "Player Capsule".
Step 11:- Arrange the cubes, Enemy and Player to create a basic map with obtstacles as
shown in the image below.

Step 12:- Select the Plane and Cubes >> Add NavMeshSurface >> And click on Bake
Step 13:- Create a C# script, named it "Enemy AI" and type the code given Below
Code:
using System.Collections;

32
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
[Range(0,50)] [SerializeField] float attackRange = 5, sightRange = 20,
timeBetweenAttacks = 3;
private NavMeshAgent thisEnemy;
public Transform playerPos;
private bool isAttacking;
private void Start()
{
thisEnemy = GetComponent<NavMeshAgent>();
}
private void Update()
{
float distanceFromPlayer = Vector3.Distance(playerPos.position,
this.transform.position);
if(distanceFromPlayer<=sightRange && distanceFromPlayer> attackRange)
{
isAttacking = false;
thisEnemy.isStopped = false;
StopAllCoroutines();
ChasePlayer();
}
if(distanceFromPlayer<=attackRange && !isAttacking)
{
thisEnemy.isStopped = true;
StartCoroutine(AttackPlayer());
}
}

33
private void ChasePlayer()
{
thisEnemy.SetDestination(playerPos.position);
}
private IEnumerator AttackPlayer()
{
isAttacking = true;
yield return new WaitForSeconds(timeBetweenAttacks);
Debug.Log("Hurt player");
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(this.transform.position, sightRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(this.transform.position, attackRange);
}
}
Step 14:- Add The Enemy AI script to Enemy Object.
Step 15:- Add the Player Capsule Object to 'Player Pos' and Adjust the Attack Range and
Sight Range and Run it
Output:-

34
35

You might also like