Files
Barrack-Unity/Assets/Scripts/Game/Shark.cs
T

120 lines
3.3 KiB
C#
Raw Normal View History

2026-08-10 21:35:53 -04:00
using UnityEngine;
2026-08-10 22:40:00 -04:00
using System.Collections;
2026-08-10 21:35:53 -04:00
public class Shark : MonoBehaviour
{
2026-08-10 22:40:00 -04:00
public AudioClip spawnSound;
public AudioClip angrySound;
public AudioClip tiredSound;
public AudioClip deathSound;
public Player player;
public SpriteRenderer gameBoardSpriteRenderer;
private Bounds gameBoardBounds;
2026-08-10 22:40:00 -04:00
private AudioSource audioSource;
private Animator animator;
private int angle = 0;
private bool isAngry = false;
private bool isTired = false;
private bool isDead = false;
private float angryTimer = 0f;
private float angryDuration = 5f;
private float angryProbability = 0.1f;
private static int sharkKillPoints = 100;
private bool spawnFinished = false;
2026-08-10 21:35:53 -04:00
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
2026-08-10 22:40:00 -04:00
audioSource = GetComponent<AudioSource>();
animator = GetComponent<Animator>();
gameBoardBounds = gameBoardSpriteRenderer.bounds;
2026-08-10 22:40:00 -04:00
bool spawnLeft = Random.Range(0, 2) == 0;
angle = spawnLeft ? 90 : 270;
animator.SetBool("spawnLeft", spawnLeft);
audioSource.PlayOneShot(spawnSound);
2026-08-10 21:35:53 -04:00
}
// Update is called once per frame
2026-08-10 22:40:00 -04:00
void FixedUpdate()
{
// Check if the spawn animation has finished.
2026-08-10 22:40:00 -04:00
if (
(animator.GetCurrentAnimatorStateInfo(0).IsName("SharkSpawnRight") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("SharkSpawnLeft")) &&
animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1.0f
)
{
spawnFinished = true;
}
// Do stuff only if the spawn animation has finished.
if (spawnFinished)
2026-08-10 22:40:00 -04:00
{
// TODO: Check if the shark was killed.
if (isDead)
{
animator.SetTrigger("killed");
audioSource.PlayOneShot(deathSound);
// TODO: award points to the player.
player.score += sharkKillPoints;
StartCoroutine(DestroyShark());
}
else
{
// TODO: Compute movement position and update the shark's speed and angle.
// TODO: Apply 2x movement speed if the shark is angry.
animator.SetInteger("angle", angle);
if (!isAngry && !isTired && Random.value < angryProbability)
{
isAngry = true;
angryTimer = angryDuration;
audioSource.PlayOneShot(angrySound);
}
if (isAngry && !isTired && angryTimer <= 0f)
{
isAngry = false;
isTired = true;
audioSource.PlayOneShot(tiredSound);
}
if (isAngry)
{
angryTimer -= Time.fixedDeltaTime;
}
}
}
}
private IEnumerator DestroyShark()
2026-08-10 21:35:53 -04:00
{
2026-08-10 22:40:00 -04:00
// Wait two loops of the death animation before destroying the shark object.
yield return new WaitUntil(
() => animator.GetCurrentAnimatorStateInfo(0).IsName("SharkDeath") &&
animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 2.0f
);
Destroy(gameObject);
2026-08-10 21:35:53 -04:00
}
}