functionality and importance
1. [Link]
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
[Link]("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. [Link]
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. [Link]
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. [Link]
Purpose: Manages the game’s pause functionality.
Key Components:
Pause: Activates a pause menu and stops game time by setting
[Link] to 0.
Resume: Hides the pause menu and resumes the game by resetting
[Link].
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. [Link]
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. [Link]
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 [Link];
using [Link];
using UnityEngine;
using [Link];
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 = [Link]("Player");
if (player != null)
target = [Link];
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
currentSpeed = initialSpeed;
SetRoamPosition();
if (enemyAudioSource == null)
enemyAudioSource = GetComponent<AudioSource>();
}
void Update()
if (target != null)
float distanceToTarget = [Link]([Link],
[Link]);
// 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 += [Link];
currentSpeed = [Link](initialSpeed - elapsedTime *
speedDecreaseRate, minSpeed);
// Move towards the target
Vector2 direction = ([Link] - [Link]).normalized;
[Link] = direction * currentSpeed;
// Optionally, update animator here
if (animator != null)
[Link]("Speed", [Link]);
}
private void Attack()
isAttacking = true;
[Link] = [Link]; // Stop movement while attacking
// Implement your attack logic here, such as dealing damage to the
player
if (animator != null)
[Link]("Attack");
// Example: Assuming the player has a script with a method
TakeDamage(int damage)
PlayerController playerHealth =
[Link]<PlayerController>();
if (playerHealth != null)
[Link](damage);
private void Roam()
// Roam around the specified radius
if ([Link]([Link], roamPosition) < 0.2f)
SetRoamPosition();
}
Vector2 direction = (roamPosition -
(Vector2)[Link]).normalized;
[Link] = direction * roamSpeed;
// Optionally, update animator here
if (animator != null)
[Link]("Speed", [Link]);
private void SetRoamPosition()
float randomX = [Link](-roamRadius, roamRadius);
float randomY = [Link](-roamRadius, roamRadius);
roamPosition = new Vector2([Link].x + randomX,
[Link].y + randomY);
private void UpdateAudioVolume(float distanceToTarget)
// Calculate volume based on distance
float volume = Mathf.Clamp01((detectionRange - distanceToTarget) /
detectionRange);
volume = [Link](volume, minVolume, maxVolume);
if (enemyAudioSource != null)
{
[Link] = volume;
using [Link];
using UnityEngine;
using [Link];
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 ([Link]("Player") && canExit)
StartCoroutine(NextLevel());
// Method to set the flag when the player interacts with the NPC
public void AllowExit()
canExit = true;
private IEnumerator NextLevel()
[Link] = slowMotion;
yield return new WaitForSeconds(delay / slowMotion); // Adjust wait time
based on slow motion
[Link] = 1f;
var currentSceneIndex = [Link]().buildIndex;
[Link](currentSceneIndex + 1);
using [Link];
using [Link];
using UnityEngine;
using [Link];
public class MainMenu : MonoBehaviour
public void PlayGame()
[Link](1);
}
public void QuitGame()
[Link] ("QUIT!");
[Link]();
using [Link];
using [Link];
using UnityEngine;
using [Link];
public class PauseMenu : MonoBehaviour
[SerializeField] public GameObject PauseMenuPanel;
// Method to pause the game
public void Pause()
[Link](true); // Activate the pause menu panel
[Link] = 0f; // Freeze game time
// Method to resume the game
public void Resume()
[Link](false); // Deactivate the pause menu panel
[Link] = 1f; // Resume game time
// Method to restart the game
public void Restart()
[Link] = 1f; // Reset time scale before restarting
[Link]("1 Main Menu"); // Load the gameplay scene
again
using UnityEngine;
using [Link];
using [Link];
using [Link]; // For scene management
using [Link];
using [Link];
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 = [Link]; // 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 = [Link]; // Set initial respawn position
if (deathSound == null)
deathSound = GetComponent<AudioSource>(); // Get AudioSource
from GameObject
[Link] = new Color(screenColor.r, screenColor.g,
screenColor.b, 0); // Transparent initially
[Link] = false; // Hide Game Over text
[Link](false); // Hide button
initially
[Link](false); // Hide continue button
initially
// Add listeners
[Link](ReturnToLobby);
[Link](ContinueToNextScene);
UpdateLivesText(); // Update UI with starting lives count
}
private void FixedUpdate()
if (canMove && !isDead)
if (movementInput != [Link])
TryMove(movementInput);
[Link]("isMoving", movementInput != [Link]);
[Link] = movementInput.x < 0;
// Handle fade-in effect
if (isFading)
currentAlpha = [Link](currentAlpha, 1f,
[Link] / fadeDuration);
[Link] = new Color(screenColor.r, screenColor.g,
screenColor.b, currentAlpha);
private bool TryMove(Vector2 direction)
if (direction != [Link])
{
int count = [Link](direction, movementFilter, new
List<RaycastHit2D>(), moveSpeed * [Link] + collisionOffset);
if (count == 0)
[Link]([Link] + direction * moveSpeed *
[Link]);
return true;
return false;
void OnMove(InputValue movementValue)
if (!isDead) // Only accept movement input if not dead
movementInput = [Link]<Vector2>(); // Corrected
parenthesis
void OnCollisionEnter2D(Collision2D collision)
if (!isDead && [Link]("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
[Link]("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)
[Link] = "Lives: " + [Link]();
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 = [Link](currentAlpha, 0f,
[Link] / fadeDuration);
[Link] = 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);
[Link] = true; // Show Game Over text
yield return new WaitForSeconds(blackScreenStayDuration);
[Link](true); // Show return to
lobby button
[Link](true); // Show continue button
private void ReturnToLobby()
[Link]("LobbyScene"); // Change to your lobby
scene name
}
private void ContinueToNextScene()
// Reset lives and player state
lives = 3;
UpdateLivesText();
// Hide Game Over UI elements
[Link] = false;
[Link](false);
[Link](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 = [Link](currentAlpha, 0f,
[Link] / fadeDuration);
[Link] = new Color(screenColor.r, screenColor.g,
screenColor.b, currentAlpha);
yield return null;
StartCoroutine(RemoveAfterAnimation());
private IEnumerator RemoveAfterAnimation()
yield return new
WaitForSeconds([Link](0).length);
yield return new WaitForSeconds(respawnDelay);
[Link] = respawnPosition; // Reset position
canMove = true;
isDead = false; // Reset dead state
movementInput = [Link]; // Reset movement input
[Link]("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 =
[Link]("Enemy");
foreach (GameObject enemy in enemies)
[Link](isActive);
using [Link];
using [Link];
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 += [Link];
if (damageTimer >= damageInterval)
damageTimer = 0f;
DealDamageToPlayer();
}
}
private void DealDamageToPlayer()
// Assuming the player has the "Player" tag
GameObject player = [Link]("Player");
if (player != null)
PlayerController playerController =
[Link]<PlayerController>();
if (playerController != null)
[Link](trapDamage);
private void OnTriggerEnter2D(Collider2D collider)
if ([Link]("Player"))
playerInRange = true;
private void OnTriggerExit2D(Collider2D collider)
{
if ([Link]("Player"))
playerInRange = false;
}string newSettingB = "Setting";
public void NewSettingButton()
[Link](newSettingB);