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

108 lines
3.0 KiB
C#

using UnityEngine;
using System.Collections;
public class Shark : MonoBehaviour
{
public AudioClip spawnSound;
public AudioClip angrySound;
public AudioClip tiredSound;
public AudioClip deathSound;
public Player player;
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;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
audioSource = GetComponent<AudioSource>();
animator = GetComponent<Animator>();
bool spawnLeft = Random.Range(0, 2) == 0;
angle = spawnLeft ? 90 : 270;
animator.SetBool("spawnLeft", spawnLeft);
audioSource.PlayOneShot(spawnSound);
}
// Update is called once per frame
void FixedUpdate()
{
// Do stuff only if the spawn animation is finished
if (
(animator.GetCurrentAnimatorStateInfo(0).IsName("SharkSpawnRight") ||
animator.GetCurrentAnimatorStateInfo(0).IsName("SharkSpawnLeft")) &&
animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1.0f
)
{
// 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()
{
// 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);
}
}