0% found this document useful (0 votes)
2 views

Functionality and Importance

The document outlines the functionality and importance of various scripts used in a game, including EnemyFollow, Exit, MainMenu, PauseMenu, PlayerController, and TrapController. Each script is responsible for specific gameplay mechanics such as enemy behavior, level transitions, user interface management, player control, and environmental hazards. These scripts collectively enhance the game's dynamics, user experience, and overall challenge.

Uploaded by

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

Functionality and Importance

The document outlines the functionality and importance of various scripts used in a game, including EnemyFollow, Exit, MainMenu, PauseMenu, PlayerController, and TrapController. Each script is responsible for specific gameplay mechanics such as enemy behavior, level transitions, user interface management, player control, and environmental hazards. These scripts collectively enhance the game's dynamics, user experience, and overall challenge.

Uploaded by

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

functionality and importance

1. EnemyFollow.cs

Purpose: This script controls the behavior of an enemy that can follow and
attack the player.

Key Components:

 Target Tracking: It finds the player using


GameObject.FindGameObjectWithTag("Player") and stores the player's
Transform as a target.

 Movement: The enemy has an initial speed that decreases over time
until it reaches a minimum speed. If the player is within a detection
range, the enemy follows the player. If the player is within an attack
range, the enemy will attack instead.

 Roaming: When the player is out of detection range, the enemy


roams within a specified radius.

 Audio Feedback: The enemy’s audio volume changes based on its


distance to the player, enhancing the gameplay experience.

 Attack Mechanism: The enemy will deal damage to the player when
within attack range.

Importance: This script provides the primary behavior for enemy


interactions, allowing for dynamic gameplay as enemies pursue and attack
the player, making the game challenging.

2. Exit.cs

Purpose: Manages the exit point for the player to transition to the next
level.

Key Components:

 Trigger Detection: The script checks for collisions with the player
using a trigger collider.

 Exit Permission: It uses a flag (canExit) to determine if the player can


exit, which can be set through other game mechanics (e.g., interacting
with an NPC).
 Level Transition: Upon triggering, it starts a coroutine that
implements a slow-motion effect, waits for a delay, and then loads the
next scene.

Importance: This script effectively handles scene transitions, allowing


players to move between levels seamlessly, thus structuring the game's
progression.

3. MainMenu.cs

Purpose: Controls the functionality of the main menu.

Key Components:

 Play Game: Loads the first game scene when the player chooses to
start the game.

 Quit Game: Logs a message to the console and closes the application.

Importance: This script is essential for managing user input from the main
menu, providing a starting point and the ability to quit the game.

4. PauseMenu.cs

Purpose: Manages the game’s pause functionality.

Key Components:

 Pause: Activates a pause menu and stops game time by setting


Time.timeScale to 0.

 Resume: Hides the pause menu and resumes the game by resetting
Time.timeScale.

 Restart: Allows the player to restart the game by loading the main
menu scene.

Importance: This script enhances the user experience by allowing players


to pause and resume the game, providing flexibility in gameplay.

5. PlayerController.cs

Purpose: Manages the player's movement, health, and interactions with the
game world.

Key Components:

 Movement Input: Handles player movement using input from the


Unity Input System, allowing for responsive controls.
 Collision Detection: Monitors collisions with enemies, triggering
damage if the player collides with them.

 Health Management: Tracks player lives, allows damage to be taken,


and handles player death.

 Game Over Logic: Manages the display of a game-over screen and


transitions back to the main menu or continues the game.

 Fade Effects: Implements fade-in and fade-out effects when


transitioning between states, enhancing visual feedback.

Importance: This script is crucial as it governs the player's core interactions


and health management, which are foundational for gameplay.

6. TrapController.cs

Purpose: Controls traps that deal damage to the player.

Key Components:

 Damage Logic: Continuously checks if the player is in range and


applies damage at defined intervals.

 Trigger Detection: Uses OnTriggerEnter2D and OnTriggerExit2D to


manage player interactions with the trap.

Importance: This script adds another layer of challenge to the game by


introducing environmental hazards that the player must avoid, enriching the
gameplay.

Summary

Each of these scripts plays a vital role in the overall game functionality:

 EnemyFollow ensures that enemies interact dynamically with the


player.

 Exit handles level transitions smoothly.

 MainMenu allows players to start or quit the game.

 PauseMenu gives players control over game interruptions.

 PlayerController manages player actions and health, which are


critical for gameplay.

 TrapController introduces environmental threats, enhancing the


challenge.
using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class ButtonUI : MonoBehaviour

[SerializeField] private using UnityEngine;

public class EnemyFollow : MonoBehaviour

private Transform target;

public float initialSpeed = 2f;

public float minSpeed = 0.5f; // Minimum speed the enemy can reach

public float speedDecreaseRate = 0.05f; // Rate at which the speed


decreases

public float detectionRange = 5f;

public float attackRange = 1f;

public float roamRadius = 10f;

public float roamSpeed = 1f;

public int damage = 10; // Damage dealt to the player

public AudioSource enemyAudioSource; // Reference to the enemy's audio


source
public float maxVolume = 1f; // Maximum volume when close to the player

public float minVolume = 0.1f; // Minimum volume when far from the
player

private float currentSpeed;

private float elapsedTime = 0f;

private Vector2 roamPosition;

private Rigidbody2D rb;

private Animator animator;

private bool isAttacking = false;

void Start()

GameObject player = GameObject.FindGameObjectWithTag("Player");

if (player != null)

target = player.transform;

rb = GetComponent<Rigidbody2D>();

animator = GetComponent<Animator>();

currentSpeed = initialSpeed;

SetRoamPosition();

if (enemyAudioSource == null)

enemyAudioSource = GetComponent<AudioSource>();
}

void Update()

if (target != null)

float distanceToTarget = Vector2.Distance(transform.position,


target.position);

// Adjust audio volume based on distance

UpdateAudioVolume(distanceToTarget);

if (distanceToTarget < attackRange)

// Attack the player

if (!isAttacking)

Attack();

else if (distanceToTarget < detectionRange)

// Follow the player

FollowTarget();

isAttacking = false; // Stop attacking when moving

}
else

// Roam around

Roam();

isAttacking = false; // Stop attacking when roaming

private void FollowTarget()

// Decrease speed over time

elapsedTime += Time.deltaTime;

currentSpeed = Mathf.Max(initialSpeed - elapsedTime *


speedDecreaseRate, minSpeed);

// Move towards the target

Vector2 direction = (target.position - transform.position).normalized;

rb.velocity = direction * currentSpeed;

// Optionally, update animator here

if (animator != null)

animator.SetFloat("Speed", rb.velocity.magnitude);

}
private void Attack()

isAttacking = true;

rb.velocity = Vector2.zero; // Stop movement while attacking

// Implement your attack logic here, such as dealing damage to the


player

if (animator != null)

animator.SetTrigger("Attack");

// Example: Assuming the player has a script with a method


TakeDamage(int damage)

PlayerController playerHealth =
target.GetComponent<PlayerController>();

if (playerHealth != null)

playerHealth.TakeDamage(damage);

private void Roam()

// Roam around the specified radius

if (Vector2.Distance(transform.position, roamPosition) < 0.2f)

SetRoamPosition();
}

Vector2 direction = (roamPosition -


(Vector2)transform.position).normalized;

rb.velocity = direction * roamSpeed;

// Optionally, update animator here

if (animator != null)

animator.SetFloat("Speed", rb.velocity.magnitude);

private void SetRoamPosition()

float randomX = Random.Range(-roamRadius, roamRadius);

float randomY = Random.Range(-roamRadius, roamRadius);

roamPosition = new Vector2(transform.position.x + randomX,


transform.position.y + randomY);

private void UpdateAudioVolume(float distanceToTarget)

// Calculate volume based on distance

float volume = Mathf.Clamp01((detectionRange - distanceToTarget) /


detectionRange);

volume = Mathf.Clamp(volume, minVolume, maxVolume);

if (enemyAudioSource != null)
{

enemyAudioSource.volume = volume;

using System.Collections;

using UnityEngine;

using UnityEngine.SceneManagement;

public class Exit : MonoBehaviour

[SerializeField] private float delay = 2f;

[SerializeField] private float slowMotion = 0.2f;

private bool canExit = false; // Flag to check if the player can exit

private void OnTriggerEnter2D(Collider2D collision)

// Check if the player has permission to exit the scene

if (collision.CompareTag("Player") && canExit)

StartCoroutine(NextLevel());

// Method to set the flag when the player interacts with the NPC
public void AllowExit()

canExit = true;

private IEnumerator NextLevel()

Time.timeScale = slowMotion;

yield return new WaitForSeconds(delay / slowMotion); // Adjust wait time


based on slow motion

Time.timeScale = 1f;

var currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

SceneManager.LoadScene(currentSceneIndex + 1);

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class MainMenu : MonoBehaviour

public void PlayGame()

SceneManager.LoadSceneAsync(1);
}

public void QuitGame()

Debug.Log ("QUIT!");

Application.Quit();

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class PauseMenu : MonoBehaviour

[SerializeField] public GameObject PauseMenuPanel;

// Method to pause the game

public void Pause()

PauseMenuPanel.SetActive(true); // Activate the pause menu panel

Time.timeScale = 0f; // Freeze game time

// Method to resume the game


public void Resume()

PauseMenuPanel.SetActive(false); // Deactivate the pause menu panel

Time.timeScale = 1f; // Resume game time

// Method to restart the game

public void Restart()

Time.timeScale = 1f; // Reset time scale before restarting

SceneManager.LoadScene("1 Main Menu"); // Load the gameplay scene


again

using UnityEngine;

using UnityEngine.InputSystem;

using UnityEngine.UI;

using UnityEngine.SceneManagement; // For scene management

using System.Collections;

using System.Collections.Generic;

public class PlayerController : MonoBehaviour

public float moveSpeed = 1f;

public float collisionOffset = 0.05f;

public ContactFilter2D movementFilter;


public int damageFromEnemy = 50; // Damage taken from enemy

public int lives = 3; // Player lives

public float respawnDelay = 2f; // Delay before respawning

public Vector3 respawnPosition; // Position to respawn the player

public FlashUI flashUI; // Reference to the FlashUI script

public AudioSource deathSound; // Reference to the AudioSource


component

// UI elements

public Image blackScreen; // Black screen Image UI

public Text gameOverText; // Game Over Text UI

public Text remainingLivesText; // Remaining Lives Text UI

public Button returnToLobbyButton; // Return to Lobby Button UI

public Button continueButton; // Continue Button UI

public Color screenColor = Color.black; // Color of the screen

public float fadeDuration = 1.0f; // Fade effect duration

public float blackScreenDelay = 0.5f; // Delay before fading in black screen

public float blackScreenStayDuration = 2.0f; // Duration to hold the black


screen

private bool isFading = false; // To control the fade in and out

private float currentAlpha = 0f; // Current alpha for fade effect

private Vector2 movementInput;

private SpriteRenderer spriteRenderer;

private Rigidbody2D rb;

private Animator animator;


private bool canMove = true;

private bool isDead = false; // Track death state

void Start()

rb = GetComponent<Rigidbody2D>();

animator = GetComponent<Animator>();

spriteRenderer = GetComponent<SpriteRenderer>();

respawnPosition = transform.position; // Set initial respawn position

if (deathSound == null)

deathSound = GetComponent<AudioSource>(); // Get AudioSource


from GameObject

blackScreen.color = new Color(screenColor.r, screenColor.g,


screenColor.b, 0); // Transparent initially

gameOverText.enabled = false; // Hide Game Over text

returnToLobbyButton.gameObject.SetActive(false); // Hide button


initially

continueButton.gameObject.SetActive(false); // Hide continue button


initially

// Add listeners

returnToLobbyButton.onClick.AddListener(ReturnToLobby);

continueButton.onClick.AddListener(ContinueToNextScene);

UpdateLivesText(); // Update UI with starting lives count


}

private void FixedUpdate()

if (canMove && !isDead)

if (movementInput != Vector2.zero)

TryMove(movementInput);

animator.SetBool("isMoving", movementInput != Vector2.zero);

spriteRenderer.flipX = movementInput.x < 0;

// Handle fade-in effect

if (isFading)

currentAlpha = Mathf.MoveTowards(currentAlpha, 1f,


Time.deltaTime / fadeDuration);

blackScreen.color = new Color(screenColor.r, screenColor.g,


screenColor.b, currentAlpha);

private bool TryMove(Vector2 direction)

if (direction != Vector2.zero)
{

int count = rb.Cast(direction, movementFilter, new


List<RaycastHit2D>(), moveSpeed * Time.fixedDeltaTime + collisionOffset);

if (count == 0)

rb.MovePosition(rb.position + direction * moveSpeed *


Time.fixedDeltaTime);

return true;

return false;

void OnMove(InputValue movementValue)

if (!isDead) // Only accept movement input if not dead

movementInput = movementValue.Get<Vector2>(); // Corrected


parenthesis

void OnCollisionEnter2D(Collision2D collision)

if (!isDead && collision.gameObject.CompareTag("Enemy"))

TakeDamage(damageFromEnemy);

public void TakeDamage(int damage)

{
if (isDead) return; // Prevent further damage if already dead

Die();

public void Die()

if (isDead) return; // Prevent triggering death multiple times

isDead = true; // Set dead state

animator.SetTrigger("Transform");

canMove = false; // Disable movement

flashUI?.Flash();

flashUI?.LoseLife();

deathSound?.Play();

lives--; // Reduce lives on death

UpdateLivesText(); // Update the lives display

if (lives <= 0)

StartCoroutine(HandleGameOverScreen());

else

StartCoroutine(HandleBlackScreen());

StartCoroutine(RemoveAfterAnimation());
}

private void UpdateLivesText()

if (remainingLivesText != null)

remainingLivesText.text = "Lives: " + lives.ToString();

private IEnumerator HandleBlackScreen()

// Deactivate enemies during black screen

ToggleEnemies(false);

yield return new WaitForSeconds(blackScreenDelay);

isFading = true; // Start fading to black

yield return new WaitForSeconds(fadeDuration); // Wait for fade in

yield return new WaitForSeconds(blackScreenStayDuration); // Hold


black screen

isFading = false; // Start fading out

currentAlpha = 1f; // Set to fully black

while (currentAlpha > 0)

currentAlpha = Mathf.MoveTowards(currentAlpha, 0f,


Time.deltaTime / fadeDuration);
blackScreen.color = new Color(screenColor.r, screenColor.g,
screenColor.b, currentAlpha);

yield return null;

ToggleEnemies(true); // Reactivate enemies

private IEnumerator HandleGameOverScreen()

yield return new WaitForSeconds(blackScreenDelay);

isFading = true; // Start fading to black

yield return new WaitForSeconds(fadeDuration);

gameOverText.enabled = true; // Show Game Over text

yield return new WaitForSeconds(blackScreenStayDuration);

returnToLobbyButton.gameObject.SetActive(true); // Show return to


lobby button

continueButton.gameObject.SetActive(true); // Show continue button

private void ReturnToLobby()

SceneManager.LoadScene("LobbyScene"); // Change to your lobby


scene name

}
private void ContinueToNextScene()

// Reset lives and player state

lives = 3;

UpdateLivesText();

// Hide Game Over UI elements

gameOverText.enabled = false;

returnToLobbyButton.gameObject.SetActive(false);

continueButton.gameObject.SetActive(false);

// Immediately show the black screen

StartCoroutine(HandleBlackScreenAfterGameOver());

private IEnumerator HandleBlackScreenAfterGameOver()

isFading = true;

currentAlpha = 1f; // Start from black

yield return new WaitForSeconds(blackScreenDelay);

while (currentAlpha > 0)

currentAlpha = Mathf.MoveTowards(currentAlpha, 0f,


Time.deltaTime / fadeDuration);

blackScreen.color = new Color(screenColor.r, screenColor.g,


screenColor.b, currentAlpha);
yield return null;

StartCoroutine(RemoveAfterAnimation());

private IEnumerator RemoveAfterAnimation()

yield return new


WaitForSeconds(animator.GetCurrentAnimatorStateInfo(0).length);

yield return new WaitForSeconds(respawnDelay);

transform.position = respawnPosition; // Reset position

canMove = true;

isDead = false; // Reset dead state

movementInput = Vector2.zero; // Reset movement input

animator.SetBool("isMoving", false); // Ensure idle animation is played

if (lives > 0)

StartCoroutine(HandleBlackScreen()); // Show black screen if lives


remain

private void ToggleEnemies(bool isActive)

GameObject[] enemies =
GameObject.FindGameObjectsWithTag("Enemy");

foreach (GameObject enemy in enemies)


enemy.SetActive(isActive);

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class TrapController : MonoBehaviour

public int trapDamage = 20; // Damage dealt by the trap

public float damageInterval = 1f; // How often the trap deals damage

private bool playerInRange = false;

private float damageTimer = 0f;

void Update()

if (playerInRange)

damageTimer += Time.deltaTime;

if (damageTimer >= damageInterval)

damageTimer = 0f;

DealDamageToPlayer();

}
}

private void DealDamageToPlayer()

// Assuming the player has the "Player" tag

GameObject player = GameObject.FindGameObjectWithTag("Player");

if (player != null)

PlayerController playerController =
player.GetComponent<PlayerController>();

if (playerController != null)

playerController.TakeDamage(trapDamage);

private void OnTriggerEnter2D(Collider2D collider)

if (collider.CompareTag("Player"))

playerInRange = true;

private void OnTriggerExit2D(Collider2D collider)


{

if (collider.CompareTag("Player"))

playerInRange = false;

}string newSettingB = "Setting";

public void NewSettingButton()

SceneManager.LoadScene(newSettingB);

You might also like