0% found this document useful (0 votes)
48 views41 pages

Mini Project Report2

Fundamentals of projets

Uploaded by

Arun KTR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views41 pages

Mini Project Report2

Fundamentals of projets

Uploaded by

Arun KTR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

BUILDING AN INTERACTIVE 2D GAME USING C#

AND UNITY
A MINI PROJECT REPORT
Submitted by

SUDHAKAR.M Reg No : 2260221


SANTHOSH KUAMR.M.C Reg No:22602209
SYED IRFAN Reg No:22602212
ROHITH.K Reg No:22602207

in partial fulfilment of the award of the degree of


BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
SCHOOL OF ENGINEERING
VELS INSTITUTE OF SCIENCE, TECHNOLOGY & ADVANCED
STUDIES(VISTAS)
PALLAVARAM, CHENNAI 600117
NOVEMBER 2024

BONAFIDE CERTIFICATE

Certified that this project “Building an interactive 2d game using c# and


Unity” is the bonafide work of SUDHAKAR.M(22602211), SANTHOSH
KUMAR.M.C(22602209), SYED IRFAN(22602212), ROHITH.K (22602207)
they carried out the project under my supervision. Certified further, that to the best
of my knowledge the work reported here does not form part of any other project
report or dissertation on the basis of which a degree or award was conferred on an
earlier occasion on this or any other candidate.

SIGNATURE SIGNATURE
Dr.K.Kalaivani ,Ph.D., Dr.R.Anandan ,Ph.D.,D.Sc.,
, Associate Professor, Professor,
Head of the department, Dept of Computer science& Engineering
Dept of Computer Science &Engineering, VISTAS,
VISTAS, Chennai – 600 117Chennai – 600 117.

Submitted for the project work and viva - voice examination held on
…………… at Vels Institute of Science, Technology and Advanced Studies
(VISTAS), Chennai – 600 117.

INTERNAL EXAMINER EXTERNAL EXAMINER


ACKNOWLEDGEMENT

It is certainly a great delight and proud privilege to acknowledge the help


and support We received from the positive minds around us in making this
venture a successful one. The infrastructural support with all kinds of lab
facilities have been a motivating factor in this completion of project work, all
because of FOUNDER & CHAIRMAN, Shri. Dr. ISHARI K. GANESH., with
great pleasure that We take this opportunity to thank him. We are grateful to our
HEAD OF THE DEPARTMENT, Dr.K.KALAIVANI , Ph.D for her continuous
support for the project, from initial advice and contacts in the early stages of
conceptual inception, and through on-going advice and encouragement to this
day.

We extend our warmest thanks to our INTERNAL GUIDE, Dr


P.Thilakavathy M.E.,Ph.D.,who has patiently guided and provided us with
invaluable advice and help. We are thankful to our Project Coordinator Ms M
Bhanumathi .

SUDHAKAR.M(22602211)
SANTHOSH KUMAR.M.C(22602209)
SYED IRFAN(22602212)
ROHITH.K (22602207)
TABLE OF CONTENTS
CHAPTER TITLE PAGE

ABSTRACT
PG.NO
1 INTRODUCTION 1
1.1 ABOUT THE PROJECT 1
2 LITERATURE SURVEY 2
3 SYSTEM ANALYSIS 3
3.1 EXISTING SYSTEM 3
3.2 PROPOSED SYSTEM 4
4 REQUIREMENT SPECIFICATION 5
4.1 INTRODUCTION 5
4.2 HARDWARE AND SOFTWARE 5
SPECIFICATIONS
4.3 TECHNOLOGIES USED 6

5 SYSTEM ARCHITECTURE 8
5.1ARCHITECTURE DIAGRAM 8
5.3 USE CASE DIAGRAM 9

6 CODING AND DATA EXTRACTION 10


6.1 CODING 10
6.2 CODING STANDARDS 10
6.3 TESTING PROCEDURE 11
7 RESULT AND OUTPUT 13
7.1OUTPUT 13
7.2 RESULT 15
8 CONCLUSION AND FUTURE WORKS 16
8.1 CONCLUSION 16
8.2FUTURE WORKS 16
9 REFERENCES 17
10 SAMPLE SOURCE CODE 18
11 BASE PAPER 23
ABSTRACT

This mini project centers on the development of a fully interactive 2D web-based


game, designed to deliver an engaging and immersive experience. The primary
objective is to create a dynamic game environment with seamless interaction,
utilizing contemporary game development techniques and tools. The project focuses
on implementing robust gameplay mechanics, intuitive controls, and visually
appealing graphics to captivate players and enhance user engagement.The
development process includes creating detailed game assets, designing user
interfaces, and integrating interactive features to ensure a cohesive and enjoyable
gameplay experience. While the core goal is to produce a polished game prototype,
there is an intention to explore future enhancements that could incorporate
educational elements, broadening the game’s functionality and impact.This project
not only demonstrates the application of game development principles but also
explores the potential for web-based games to offer versatile and engaging
experiences. The final prototype serves as a foundation for further development and
experimentation in both interactive and educational game design.
CHAPTER 1
INTRODUCTION
The ability to create engaging and interactive experiences is central to the field of
game development, and understanding player engagement through effective game
design can transform how users experience games. This project focuses on developing
a 2D game in Unity, showcasing various game mechanics and design principles to
offer players a captivating and immersive experience.

1.1ABOUT THE PROJECT

Our project, titled [BUILDING AN INTERACTIVE 2D GAME USING C# AND UNITY

], aims to build a dynamic 2D game environment using Unity,

targeting core aspects of gameplay such as health management, scoring, and enemy interaction.

This mini-project leverages the Unity engine and C# scripting to bring these mechanics to life,

with an emphasis on creating a seamless, engaging, and technically robust game.We have implemented

various elements crucial to gameplay. A health bar and scoring system track player performance

, while collision mechanics allow for realistic interactions between the player and enemies. The

game’s development involved iterative testing and optimization, focusing on smooth player

movement, responsive controls, and a user-friendly interface.Our project follows a structured

approach, including data-driven design and code refinement. Scripts are tested for performance and

optimized to reduce runtime errors, ensuring a consistent gameplay experience. Key mechanics such

as health reduction upon enemy collision are meticulously integrated to provide challenge and maintain

player interest. This project transcends technical skill, reflecting a commitment to both user

engagement and smooth gameplay. Moving forward, future improvements could include more

complex AI behaviors, additional game levels, and refined visuals to enhance the player's

experience.By focusing on these fundamental aspects, this project aims to offer a practical learning

experience in game development, setting a strong foundation for building more complex, engaging

games in the future.

1
CHAPTER 2
LITERATURE SURVEY
Literature Survey 1:
Title: "Fox Fables: An Adventure-Based 2D Game in Unity Game Engine"
This survey explores the creation and design principles of Fox Fables, a 2D
adventure game developed using the Unity engine. The game combines
storytelling with engaging gameplay elements, focusing on a fox character's
journey through various landscapes filled with challenges and puzzles. The
authors discuss the techniques used to achieve smooth movement, collision
detection, and interactive gameplay mechanics within a 2D framework.
They analyze the strengths of Unity's asset management, scripting capabilities, and
animation tools in creating a visually appealing and interactive environment.
Key challenges identified in the development of Fox Fables include optimizing
graphics for various platforms, balancing difficulty to maintain player
engagement, and achieving responsive controls. The study highlights the
importance of cohesive level design and thoughtful character development in
fostering an immersive experience. This survey is a useful resource for
developers and designers looking to understand the intricacies of creating a
cohesive 2D adventure game in Unity, offering insights into both the creative
and technical aspects of the process.

Literature Survey 2:
Title: "The Role of Game Engines in Game Development and Teaching".

This literature survey examines the critical role game engines play in both
professional game development and educational settings. It provides an in-depth
analysis of popular game engines like Unity and Unreal Engine, focusing on their
capabilities in creating immersive 2D and 3D experiences, simplifying complex
programming tasks, and enabling rapid prototyping. The authors highlight the
accessibility and versatility of these tools, which make them invaluable for
beginners and experienced developers alike.
In addition to exploring technical benefits, the study addresses the pedagogical
advantages of using game engines in teaching environments. By providing a
hands-on approach, game engines help students and aspiring developers gain
practical experience, from scripting and asset management to gameplay testing and
iteration. Challenges discussed include the steep learning curve for beginners and the
necessity for balancing theoretical knowledge with practical application.
This survey emphasizes the transformative impact of game engines on learning and
creativity in game development, serving as a comprehensive guide for
educators and developers aiming to harness these tools effectively.

2
CHAPTER 3
SYSTEM ANALYSIS
3.1EXISTING SYSTEM
Existing 2D game development systems and frameworks provide essential insights and
serve as inspiration for our Unity-based project. Below are some of the notable tools,
platforms, and game development trends that have influenced the development of our
game:

1. Unity Game Engine: Unity is a widely used game development platform,


especially popular for 2D and 3D game projects. Its asset store, extensive
documentation, and scripting flexibility make it ideal for indie developers and
large studios alike. Unity’s real-time rendering, physics engine, and
multi-platform compatibility offer significant benefits for building games
quickly and efficiently.

2. Godot Engine: Godot is an open-source game engine that has gained popularity
due to its lightweight framework and user-friendly interface, especially for
2D games. While it may not have as extensive an asset store as Unity, it provides
an intuitive approach to scene management and scripting that many developers
find beneficial.

3. RPG Maker: RPG Maker specializes in creating 2D role-playing games and


offers a simplified drag-and-drop interface for designing levels and characters.
Although it’s highly specialized, it serves as a reference for creating engaging
storytelling mechanisms within 2D environments.

4. Popular 2D Indie Games: Games such as Celeste and Hollow Knight set
benchmarks in 2D game design by showcasing unique art styles, smooth
movement mechanics, and engaging gameplay. These games highlight the
importance of a cohesive aesthetic, well-designed levels, and finely tuned
difficulty for maintaining player engagement.

5. Multiplayer and Online Features in 2D Games: Many modern 2D games are


incorporating online or multiplayer elements, allowing players to interact and
compete. Unity’s networking capabilities serve as a useful reference for
developers looking to integrate similar features.

6. Commercial Success Stories: Successful 2D games, especially those created by


indie studios, demonstrate the viability of smaller projects in the gaming market.
Games like Stardew Valley exemplify how polished mechanics, engaging
storylines, and solid artwork can lead to commercial success.
3
3.2PROPOSED SYSTEM
Our proposed system aims to create an immersive 2D adventure game using Unity,
focusing on gameplay mechanics such as health management, scoring,
and enemy interactions. The main objectives and components of the system include:
1. Player Movement and Control: A responsive movement system allows the player to
navigate the game environment smoothly. This involves collision detection, a
user-friendly control scheme, and animations that enhance the player experience.

2. Health and Scoring System: Our game incorporates a health bar and scoring system
to track player progress and add challenge. The health bar decreases upon collision
with enemies, providing visual feedback on the player's status, while the scoring
system rewards progress and motivates continued play.

3. Collision Detection and Interaction:


Implemented with Unity’s physics engine, our system allows for realistic interactions
between the player and various in-game elements, such as obstacles and enemies.
This adds an extra layer of realism and challenge to the gameplay.

4. Visual and Audio Assets: The project utilizes a range of 2D assets and sound effects
that align with the game’s theme and enhance the overall ambiance. Custom sprites
and sound effects were incorporated to create a unique and engaging environment.

5. Future Expansion and Customization: The game is designed with scalability in


mind, allowing for potential expansion with additional levels, characters, and features.
This modular approach enables further development based on player feedback and
testing results.

Through these components, the proposed system strives to provide a dynamic and
enjoyable experience for players, while also serving as a valuable learning tool for
the developers involved in creating interactive 2D games with Unity.

4
CHAPTER 4
REQUIREMENT SPECIFICATION
4.1INTRODUCTION
The requirement specifications for developing a 2D game in Unity cover both
hardware and software essentials that ensure smooth operation and efficient game
development. Since Unity is a powerful game engine, the hardware specifications
must meet a certain threshold to support rendering, scripting, and real-time game
testing. Additionally, specific software tools and frameworks are necessary for
creating, testing, and deploying the game. These requirements allow for seamless
asset handling, code management, and project scalability, ensuring that the project
runs optimally during development and on target platforms.

4.2HARDWARE AND SOFTWARE SPECIFICATIONS


HARDWARE COMPONENTS
• Hard Disk: 500GB and above

• RAM: 8GB and Above

• Processor: I5 and Above

SOFTWARE COMPONENTS
 Operating System: Windows 10 (64-bit), Windows 11, or macOS
(for compatibility with Unity)

 Unity Version: Unity 2021.3 LTS or later (for stability and access to the
latest 2D development features)

 Programming Language: C# (Unity’s scripting language for game


development)

 IDE: Visual Studio 2019 or later (recommended for Unity projects, as it


integrates well with Unity for scripting and debugging)

 Additional Tools:
5
o Unity Asset Store (for free and paid assets to aid in rapid
development)

o Adobe Photoshop or GIMP (for creating or editing 2D game


assets)
o Audacity (for sound editing, if custom sound effects are needed)

4.3TECHNOLOGIES USED
4.3.1UNITY
Unity is a powerful, cross-platform game development engine widely used for
creating both 2D and 3D games. Released by Unity Technologies, Unity has gained
popularity due to its ease of use, vast community support, and extensive library of
assets. It empowers developers to create games quickly, with tools for rendering,
physics, and scripting. Unity’s versatility also makes it a preferred choice for VR and
AR applications, simulations, and interactive media.

Unity is used for:

 Game Development: Unity supports 2D and 3D game creation, providing


tools for animation, lighting, and physics.

 Simulations: Used for creating virtual simulations in industries like


automotive, architecture, and education.

 Augmented and Virtual Reality (AR/VR): Unity’s robust platform supports


immersive VR and AR experiences.

 Prototyping: Unity’s rapid prototyping capabilities make it ideal for


early-stage development and testing.

What can Unity do?

 Cross-Platform Deployment: Unity supports building games for multiple


platforms, including PC, consoles, mobile, and VR devices.

 Scripting and Automation: Unity uses C# as its scripting language,

6
allowing for a robust, object-oriented programming environment.

 Real-Time Rendering: Unity’s real-time rendering engine enables the


creation of high-quality graphics.

 Physics and Animation: Built-in physics and animation systems allow for
Realistic game dynamics.

 Asset Management: Unity's Asset Store offers a wide range of pre-made


assets, reducing the need to create everything from scratch.

Why Unity?

 Cross-Platform Compatibility: Unity allows developers to create games that can


run on Windows, macOS, Android, iOS, and major gaming consoles.

 Visual Interface: Unity’s user-friendly editor provides a drag-and-drop interface


for game objects and UI elements, making development more accessible.

 Large Community: Unity boasts a large user community and extensive


documentation, which aids in troubleshooting and development.

 Continuous Updates: Unity receives frequent updates and improvements,


providing developers with the latest tools and features.

 Asset Store: Unity’s Asset Store enables developers to purchase or download free
assets, including scripts, models, and plugins.

 Learning Resources: Unity offers free tutorials and courses, making it easier for
beginners to get started.

Integrated Development Environment (IDE):


 Unity is typically used in conjunction with Visual Studio or Rider for C#
scripting, providing robust tools for coding, debugging, and testing.

Unity Syntax and Development Cycle:


 Unity projects are organized around scenes, which contain game objects with
attached components (such as scripts, colliders, and renderers).
 Game Logic: Unity scripts are written in C#, allowing developers to create
interactive gameplay, AI behavior, and UI functionality.
 Game Loop: Unity follows an event-driven model with a game loop, calling
specific functions (e.g., Update and FixedUpdate) on each frame to handle
game logic.

7
CHAPTER 5
SYSTEM ARCHITECTURE
5.1ARCHITECTURE DIAGRAM
A Architecture Diagram is simply a graphical representation of
steps. It shows steps in sequential order and is widely used in presenting the flow of
algorithms, workflow, or processes. Typically, a flowchart shows the steps as boxes
of various kinds, and their order by connecti
connecting them with arrows.

Fig 5.1: Architecture diagram of 2d Game.

5.3USE DIAGRAM

A Use Case Diagram visually represents the system's functionality and the key actions
that can be performed within the system. In the context of our game, the use case
diagram outlines important game features and interactions that the player can engage
with during gameplay. These include various gameplay mechanics, menus, and triggers
that enhance the user experience.

The diagram focuses on core actions and events that take place in the game, such as
accessing the start menu, pausing the game, or interacting with game objects.
In this use case diagram, several key functionalities are illustrated to showcase how
playerss can interact with the game and trigger various events:

8
1. Start Menu:: The player can access the start menu to begin the game or
navigate to other options like settings, load game, or quit.
2. Pause Menu:: During gameplay, the player can pause the game to acceaccess the
pause menu, which includes options like resume, restart, or adjust game settings.

3. When Trigger:: This use case represents events that occur when certain
conditions are met, such as entering a new area, interacting with objects, or
completing a quest.
est. Triggers can activate dialogues, open doors, or change
the game environment.

4. Object Collection:: The player can collect items or interact with objects within
the game. This could include picking up keys, treasures, or power
power-ups, which
are essential for progressing through the game.

Fig 5.2:: Use Case Diagram for 2D Game.

9
CHAPTER 6
CODING AND TESTING
6.1CODING

Once the design of the system is finalized, the next phase involves coding and testing.
This phase brings the system to life by converting the designed architecture into
executable code using the chosen programming language. It is essential to follow a well-
organized coding approach, ensuring that modifications can be easily integrated into the
system whenever required. Good coding practices make the development process
smoother and help maintain the code in the long run.

Coding Standards
Coding standards serve as guidelines for writing code in a structured and readable way.
Adhering to these standards ensures that the code is easy to understand, debug, and
maintain. Properly following coding standards during the development phase ensures
that any programmer can comprehend the code and implement changes effectively.
Essential coding standards include:
 Writing simple, clear, and understandable code.
 Proper naming conventions for variables, functions, and classes.
 Consistent handling of error messages and exceptions.
 Proper script formatting with necessary indentation and commenting.
 Structured message box formats for clear communication with the user.

Naming Conventions
Following consistent naming conventions is crucial to ensure that the code is
self-descriptive and easily understandable. The names of classes, data members,
functions, and variables should indicate their purpose. For example:
 Class Names: Should begin with a capital letter and use camel case (e.g.,
MainCharacter).
 Member Functions and Data Members: Should begin with a lowercase letter,
and subsequent words should be capitalized (e.g., playerHealth or
moveCharacter).

Value Conventions
Value conventions focus on assigning and validating appropriate values to variables
during runtime. These conventions ensure that the system behaves as expected and
that no erroneous values are used. Key points include:
 Defining proper default values for variables.
 Validating input values to prevent errors.
 Documenting flag values for clarity.

Script Writing and Commenting Standards


Proper indentation is crucial for script readability. Each conditional or looping statement
10
should be properly aligned for clarity. Comments should be included to explain the logic
behind complex sections of code and to avoid misunderstandings when revisiting the
code later.

Message Box Format


When the system communicates with the user, it’s vital that the message is clear and
easy to understand. A standardized message box format helps ensure this:
 X: Indicates an illegal operation by the user.
 !: Provides information to the user, such as updates or notifications.

Testing Procedure
System Testing
Testing plays a critical role in software development as it helps identify errors and
ensures the system functions as intended. It is a quality assurance process that verifies
the system’s compliance with the design specifications. System testing aims to confirm
that the software performs as expected and adheres to the design. This process also
includes inspecting the design before coding starts, as any detected design errors are
easier to fix earlier in the process, saving time and resources.

Test Data and Output


Unit Testing
Unit testing verifies the functionality of individual components of the software, also
known as modules. This testing ensures that each part of the program works as
intended in isolation. White-box testing techniques are commonly employed during unit
testing.

Functional Tests
Functional testing verifies the correctness of the system’s functionality. Test cases
involve testing with standard input values, boundary values, and edge cases, such as
empty files or logically related inputs.
 Performance Test: Evaluates the execution time and efficiency of the software.
 Stress Test: Tests the software under extreme conditions to determine how it
 handles high loads or unusual inputs.
 Structure Test: Focuses on testing the internal logic of the system and ensuring
 that all paths and decision points within the code are properly executed.

Integration Testing
Integration testing focuses on combining individual modules and verifying their
interaction and communication. This helps uncover errors that occur when different
parts of the system interact with each other. Modules are tested incrementally to identify
and fix issues early. The goal is to detect interface errors and ensure seamless module
integration before proceeding to the user acceptance stage.

Testing Techniques and Strategies


11
Testing ensures the correctness of the system before its final deployment. Two main
testing methodologies are used:
 White-box Testing: Also known as glass-box testing, this method tests the
internal logic and functions of the program. The tester creates test cases based on
the code’s control structure, ensuring that all paths and logic conditions are
covered. This includes techniques like basis path testing, which ensures all
logical decisions are executed.

 Black-box Testing: This testing approach focuses on the system’s external


behavior rather than its internal workings. The goal is to ensure that the system
meets the functional requirements outlined in the specification.

Security Testing
Security testing ensures the system is protected against potential vulnerabilities. This
involves verifying the protection mechanisms of the system to prevent unauthorized
access or breaches. During security testing, the tester simulates attacks to check how the
system defends itself against them.

Validation Testing
At the culmination of integration testing, the software undergoes validation testing. The
goal is to ensure that the software functions as expected from the user's perspective.
Validation testing checks whether the system’s behavior aligns with the user’s
requirements. If any discrepancies are found, they are corrected before final
delivery.

User Acceptance Testing


User acceptance testing is critical for the success of any system. It ensures that the
system meets the user’s needs and requirements. During this phase, the system is
tested for usability, input/output screen design, and overall performance. The system is
refined based on feedback and adjustments are made to improve user experience.

12
CHAPTER 7
RESULT AND OUTPUT
7.1OUTPUT
The game application begins by loading the main menu, where players can
start the game, access the pause menu, or adjust settings. The input system is
designed to handle various actions such as player movement, interactions with
enemies, and triggering events. The key mechanics such as health bars, scoring,
and game events are dynamically updated as the game progresses.

START MENU:

13
BASIC GAMEPLAY:

PAUSE MENU:

In the game, player interactions with different in-game objects trigger actions like
health reduction, triggering animations, or updating the score. For instance,
when the player collides with an enemy, the health bar decreases accordingly.
The game is built to allow fluid transitions between different game states such as
start, in-game, and pause menus, ensuring a seamless experience for the user.
14
GAMEPLAY MECHANICS:

7.2RESULT

The performance of the game has been tested by running several simulations,
including scenarios where the player interacts with various game objects.
The response times for actions like health bar updates, score updates, and menu
transitions have been within acceptable limits. Most of the time spent in the game is
during the actual gameplay when the player engages in combat with enemies or
navigates through different levels. The game handles inputs such as
movement and interactions with minimal delay, providing a responsive and engaging
player experience.
The game is optimized for smooth performance, with minimal lag during the core
gameplay. The pause menu, start menu, and event triggers all work as expected,
and the overall flow of the game is stable. Minor bugs and glitches observed during
testing have been addressed, ensuring a polished final product.

15
CHAPTER 8
CONCLUSION AND FUTURE WORKS
8.1CONCLUSION

In conclusion, our project on "2D Game Development Using Unity" represents a


substantial effort to design an interactive, engaging, and functional game experience
in a 2D environment. Through Unity's powerful tools and scripting capabilities, we
crafted a visually appealing game that integrates essential features like responsive
player controls, collision detection, and health and scoring systems. This project
emphasizes the effectiveness of Unity as a platform for indie and professional game
development, providing a streamlined workflow from design to deployment. Our
work not only highlights Unity’s potential but also the immense value of well-
structured game mechanics and user-centered design, laying the foundation for
further innovation in 2D gaming..
8.2FUTURE WORKS

Looking forward, several areas hold promise for expanding and refining our project.
Future developments could involve incorporating more complex animations,
enhanced AI for NPCs, and additional levels to increase player engagement and
challenge. Integrating multiplayer functionality would broaden the game's appeal,
while cross-platform compatibility could make it accessible to a wider audience.
Additionally, we aim to explore more advanced game mechanics, such as
procedurally generated content and more dynamic in-game environments. Through
these improvements, we strive to create an even more immersive and versatile
gaming experience, keeping pace with industry advancements and player
expectations..

16
CHAPTER 9

REFRENCES
• Rollings, A., & Adams, E. (2003). Andrew Rollings and Ernest Adams on Game
Design. New Riders.
• Juul, J. (2011). Half-Real: Video Games between Real Rules and Fictional Worlds.
MIT Press.

• Zubek, R. (2020). Elements of Game Design. MIT Press.


• Sweetser, P., Johnson, D., & Wyeth, P. (2012). "A Theoretical Framework and
Methodology for Examining Game Usability." International Journal of Human-
Computer Interaction, 28(6), 411-431.
• Isbister, K., & Schaffer, N. (2008). Game Usability: Advancing the Player Experience.
CRC Press.
• Adams, E. (2014). Fundamentals of Game Design (3rd ed.). New Riders.
• Salen, K., & Zimmerman, E. (2004). Rules of Play: Game Design Fundamentals. MIT
Press.
• Novak, J. (2011). Game Development Essentials: An Introduction (3rd ed.). Cengage
Learning.
• Fullerton, T. (2018). Game Design Workshop: A Playcentric Approach to Creating
Innovative Games (4th ed.). CRC Press.
• Schell, J. (2020). The Art of Game Design: A Book of Lenses (3rd ed.). CRC Press.

17
CHAPTER 10
SAMPLE SOURCE CODE

MAIN SOURCE CODING

CameraFollow.cs

using UnityEngine;

public class CameraFollow : MonoBehaviour


{
public Transform target; // Assign the player object here
public Vector3 offset; // Offset position of the camera

void LateUpdate()
{
// Update the camera's position to follow the player with the specified offset
transform.position = target.position + offset;
}
}

Enemy.cs

using UnityEngine;

public class Enemy : MonoBehaviour


{
void OnCollisionEnter2D(Collision2D collision)
{
// Check if the object collided with is tagged as "Player"
if (collision.gameObject.CompareTag("Player"))
{
// Get the PlayerHealth component from the player
PlayerHealth playerHealth =
collision.gameObject.GetComponent<PlayerHealth>();

if (playerHealth != null)
{
// Deal damage to the player
playerHealth.TakeDamage(playerHealth.damageAmount);
18
}
}
}
}

MainMenu.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour


{
public void PlayGame()
{
SceneManager.LoadSceneAsync(1);
}
public void BackGame()
{
SceneManager.LoadSceneAsync(0);
}
public void QuitGame()
{
Application.Quit();
}
}

Movement.cs

using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

public class Movement : MonoBehaviour


{
public float moveSpeed=5f;

public Rigidbody2D rb;


19
public Animator animator;
public GameObject projectilePrefab; // The projectile prefab to spawn
public Transform firePoint; // The point from where the projectile will
be fired
public float projectileSpeed = 10f;
private Vector2 movementDirection;

Vector2 movement;

// Update is called once per frame


void Update()
{
movement.x=Input.GetAxisRaw("Horizontal");
movement.y=Input.GetAxisRaw("Vertical");

animator.SetFloat("Horizontal",movement.x);
animator.SetFloat("Vertical",movement.y);
animator.SetFloat("Speed",movement.sqrMagnitude);
movementDirection = new Vector2(Input.GetAxis("Horizontal"),
Input.GetAxis("Vertical"));

if (Input.GetKeyDown(KeyCode.Space))
{
ShootProjectile();
}

}
void ShootProjectile()
{
if (movementDirection != Vector2.zero)
{
// Create the projectile at the fire point
GameObject projectile = Instantiate(projectilePrefab, firePoint.position,
Quaternion.identity);

// Set the projectile's velocity in the direction the player is moving


Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
rb.velocity = movementDirection.normalized * projectileSpeed;
}
}
20
void FixedUpdate()
{
rb.MovePosition(rb.position + movement *moveSpeed *
Time.fixedDeltaTime);
}
}

PlayerHealth.cs

using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour


{
public int maxHealth = 100; // Maximum health of the player
public int currentHealth; // Current health of the player
public Slider healthBarSlider; // Reference to the health bar slider
public GameObject gameOverPanel; // Reference to the Game Over panel
public int damageAmount = 20; // Amount of health to reduce when hit by
an enemy

void Start()
{
// Initialize current health to max health at the start
currentHealth = maxHealth;
healthBarSlider.maxValue = maxHealth;
healthBarSlider.value = currentHealth;
gameOverPanel.SetActive(false); // Hide Game Over panel at the start
}

public void TakeDamage(int damage)


{
// Reduce the current health by the damage amount
currentHealth -= damage;

// Update the health bar UI


healthBarSlider.value = currentHealth;

// Check if health is zero or less


if (currentHealth <= 0)
{
21
// Show Game Over panel
gameOverPanel.SetActive(true);

// Destroy the player object


Destroy(gameObject);
}
}
}

Projectile.cs

using UnityEngine;

public class projectile : MonoBehaviour


{
void OnTriggerEnter2D(Collider2D collision)
{
// Check if the object hit is tagged as "Enemy"
if (collision.CompareTag("enemy"))
{
// Destroy the enemy object
Destroy(collision.gameObject);

// Destroy the projectile


Destroy(gameObject);
}
}

// Destroy the projectile after a certain time if it doesn't hit anything


private void Start()
{
Destroy(gameObject, 5f); // Destroy after 5 seconds to prevent endless
projectiles
}
}

22
CHAPTER 11
Base Papers

23
24
25
26
27
28
29
30
31
32
33
34
35

You might also like