MiniGames/Assets/Scripts/WhackAMole/WhackAMoleGameManager.cs
2025-07-14 14:28:21 +05:00

106 lines
2.9 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using TMPro;
using DG.Tweening;
public class WhackAMoleGameManager : MonoBehaviour
{
public Mole[] moles;
public float spawnInterval = 1.5f;
public float gameDuration = 30f;
public TextMeshProUGUI scoreText;
public TextMeshProUGUI timerText;
public GameObject hammerPrefab;
public Transform[] moleHammerPositions;
private int score = 0;
private float timeLeft;
private Camera mainCamera;
void Start()
{
mainCamera = Camera.main;
timeLeft = gameDuration;
InvokeRepeating(nameof(SpawnMole), 1f, spawnInterval);
}
void Update()
{
timeLeft -= Time.deltaTime;
timerText.text = "Time: " + Mathf.CeilToInt(Mathf.Max(timeLeft, 0f));
if (timeLeft <= 0f)
{
CancelInvoke(nameof(SpawnMole));
return;
}
// Check for click
if (Input.GetMouseButtonDown(0))
{
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Mole mole = hit.collider.GetComponent<Mole>();
if (mole != null && mole.IsVisible())
{
mole.ReactToHit();
int moleIndex = System.Array.IndexOf(moles, mole);
InstantiateHammerAtMole(moleIndex);
}
else
{
InstantiateHammerAtClick(hit.point);
}
}
}
}
void SpawnMole()
{
if (moles.Length == 0) return;
int index = Random.Range(0, moles.Length);
moles[index].Show();
}
public void AddScore(int points)
{
score += points;
scoreText.text = "Score: " + score;
}
void InstantiateHammerAtMole(int index)
{
if (index < 0 || index >= moleHammerPositions.Length) return;
Transform hammerPos = moleHammerPositions[index];
GameObject hammer = Instantiate(hammerPrefab, hammerPos.position, hammerPos.rotation);
AnimateHammerMesh(hammer);
}
void InstantiateHammerAtClick(Vector3 position)
{
Quaternion referenceRotation = moleHammerPositions[0].rotation;
// Calculate lifted position using the reference's up direction
Vector3 liftedPosition = position + referenceRotation * Vector3.up * 0.5f;
GameObject hammer = Instantiate(hammerPrefab, liftedPosition, referenceRotation);
AnimateHammerMesh(hammer);
}
void AnimateHammerMesh(GameObject hammer)
{
Transform meshHammer = hammer.transform.GetChild(0); // assumes first child is the mesh
meshHammer.localEulerAngles = new Vector3(-150f, 0f, 0f);
meshHammer.DOLocalRotate(Vector3.zero, 0.2f).SetEase(Ease.OutBack);
// Optional: Destroy hammer after animation
Destroy(hammer, 0.5f);
}
}