Files
Barrack-Unity/Assets/Scripts/Game/Yummies/YummyBase.cs
T

117 lines
2.7 KiB
C#
Raw Normal View History

2026-08-06 14:43:17 -04:00
using UnityEngine;
using System.Collections;
2026-08-06 14:43:17 -04:00
2026-08-27 22:05:44 -04:00
public abstract class YummyBase : NotifierBase
2026-08-06 14:43:17 -04:00
{
public AudioClip bounceSound;
public AudioClip obtainedSound;
public AudioClip missedSound;
private AudioSource audioSource;
private Animator animator;
private SpriteRenderer spriteRenderer;
private Vector2 speed;
private bool isObtained = false;
private float missedTimer = 0f;
private bool isMissed = false;
2026-08-06 14:43:17 -04:00
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
animator = GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
spriteRenderer = GetComponent<SpriteRenderer>();
speed = new Vector2(Random.Range(-0.05f, 0.05f), Random.Range(-0.05f, 0.05f)).normalized * 0.05f;
}
// Update is called once per frame
void FixedUpdate()
{
if (isObtained || isMissed)
2026-08-06 14:43:17 -04:00
{
return;
}
2026-08-19 13:18:26 -04:00
// Force reset the rotation.
transform.rotation = Quaternion.identity;
2026-08-06 14:43:17 -04:00
transform.Translate(speed);
missedTimer += Time.fixedDeltaTime;
if (missedTimer >= 5f && !isMissed)
2026-08-06 14:43:17 -04:00
{
isMissed = true;
2026-08-06 14:43:17 -04:00
audioSource.PlayOneShot(missedSound);
animator.SetTrigger("missed");
StartCoroutine(DestroyYummy());
2026-08-06 14:43:17 -04:00
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (isObtained)
{
return;
}
if(other.gameObject.CompareTag("Bar"))
{
var player = GameObject.FindGameObjectWithTag("Player");
2026-08-19 13:18:26 -04:00
Obtain(player.GetComponent<Player>());
2026-08-06 14:43:17 -04:00
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall"))
{
ContactPoint2D contact = collision.GetContact(0);
speed = Vector2.Reflect(speed, contact.normal);
audioSource.PlayOneShot(bounceSound);
}
else
{
Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>(), true);
}
}
public IEnumerator DestroyYummy()
2026-08-06 14:43:17 -04:00
{
yield return new WaitForSeconds(1.5f);
2026-08-06 14:43:17 -04:00
Destroy(gameObject);
}
2026-08-19 13:18:26 -04:00
public void AwardToPlayer(Player player)
{
Obtain(player);
}
private void Obtain(Player player)
{
if (isObtained || isMissed)
{
return;
}
audioSource.PlayOneShot(obtainedSound);
if (player != null)
{
ObtainedCallback(player);
}
isObtained = true;
spriteRenderer.enabled = false;
}
2026-08-06 14:43:17 -04:00
protected abstract void ObtainedCallback(Player player);
}