93 lines
2.3 KiB
C#
93 lines
2.3 KiB
C#
using UnityEngine;
|
|
using System.Collections;
|
|
|
|
public class GlassBall : MonoBehaviour
|
|
{
|
|
private Animator animator;
|
|
|
|
public AudioClip spawnSound;
|
|
|
|
public AudioClip bounceSound;
|
|
|
|
public AudioClip hitSound;
|
|
|
|
public AudioClip breakSound;
|
|
|
|
private AudioSource audioSource;
|
|
|
|
private Vector2 speed;
|
|
|
|
private int health = 3;
|
|
|
|
private SpriteRenderer spriteRenderer;
|
|
|
|
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
|
void Start()
|
|
{
|
|
audioSource = GetComponent<AudioSource>();
|
|
animator = GetComponent<Animator>();
|
|
spriteRenderer = GetComponent<SpriteRenderer>();
|
|
speed = new Vector2(Random.Range(-0.05f, 0.05f), Random.Range(-0.05f, 0.05f));
|
|
|
|
audioSource.PlayOneShot(spawnSound);
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void FixedUpdate()
|
|
{
|
|
AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);
|
|
|
|
if (stateInfo.IsName("GlassBallMove1") ||
|
|
stateInfo.IsName("GlassBallMove2") ||
|
|
stateInfo.IsName("GlassBallMove3"))
|
|
{
|
|
transform.Translate(speed);
|
|
}
|
|
}
|
|
|
|
void OnCollisionEnter2D(Collision2D collision)
|
|
{
|
|
if (collision.gameObject.CompareTag("Wall") ||
|
|
collision.gameObject.CompareTag("GlassBall"))
|
|
{
|
|
ContactPoint2D contact = collision.GetContact(0);
|
|
speed = Vector2.Reflect(speed, contact.normal);
|
|
|
|
// Glass balls take damage when colliding with other GlassBalls
|
|
// TODO: Check for collisions with a bar.
|
|
if (collision.gameObject.CompareTag("GlassBall"))
|
|
{
|
|
health--;
|
|
|
|
if (health < 0)
|
|
{
|
|
health = 0;
|
|
}
|
|
|
|
animator.SetInteger("health", health);
|
|
|
|
if (health > 0)
|
|
{
|
|
audioSource.PlayOneShot(hitSound);
|
|
} else
|
|
{
|
|
audioSource.PlayOneShot(breakSound);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Break()
|
|
{
|
|
spriteRenderer.enabled = false;
|
|
StartCoroutine(BreakCoroutine());
|
|
}
|
|
|
|
private IEnumerator BreakCoroutine()
|
|
{
|
|
yield return new WaitForSeconds(0.6f);
|
|
|
|
Destroy(gameObject);
|
|
}
|
|
}
|