Files
fish-escape/Assets/Scripts/FishCollector.cs
James Hodgson a8b5c87285 Add score
2022-04-13 23:21:15 +01:00

96 lines
2.6 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FishCollector : MonoBehaviour
{
public GameObject collectiblesContainer;
public Text scoreText;
// Total score of all collectibles
public int totalScore = 0;
private int maxScore = 0;
Collectible[] collectibles;
Renderer r;
CharacterController cc;
// Start is called before the first frame update
void Start()
{
r = GetComponent<Renderer>();
cc = GetComponent<CharacterController>();
collectibles = collectiblesContainer.GetComponentsInChildren<Collectible>();
foreach (Collectible collectible in collectibles)
{
maxScore += collectible.score;
}
UpdateUI();
}
void Update()
{
Vector3 fishPosition = r.bounds.center;
foreach (Collectible collectible in collectibles)
{
if (collectible.collected || !collectible.isEnabled)
{
// Skip collectibles already collected or disabled
continue;
}
Renderer collectibleRenderer = collectible.GetComponent<Renderer>();
float collectibleRadius = collectibleRenderer.bounds.extents.magnitude;
Vector3 collectiblePosition = collectibleRenderer.bounds.center;
bool x = false;
bool y = false;
bool z = false;
// Check if we are colliding with the collectible
if (fishPosition.x >= collectiblePosition.x - collectibleRadius &&
fishPosition.x <= collectiblePosition.x + collectibleRadius)
{
x = true;
}
if (fishPosition.y >= collectiblePosition.y - collectibleRadius &&
fishPosition.y <= collectiblePosition.y + collectibleRadius)
{
y = true;
}
if (fishPosition.z >= collectiblePosition.z - collectibleRadius &&
fishPosition.z <= collectiblePosition.z + collectibleRadius)
{
z = true;
}
if (x && y && z)
{
totalScore += collectible.score;
collectible.Collect();
// Update UI
UpdateUI();
// Assume we aren't colliding with 2 at the same time!
break;
}
}
}
void UpdateUI()
{
scoreText.text = String.Format("Score: {0}/{1}", totalScore, maxScore);
}
}