Finish the puzzling. Add the cup level

This commit is contained in:
WillJeynes
2026-08-27 12:54:16 +01:00
parent 596571f493
commit 3ca0c5330f
13 changed files with 403 additions and 183 deletions
+87
View File
@@ -0,0 +1,87 @@
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using Utils;
using Random = UnityEngine.Random;
public class CupShuffle : Singleton<CupShuffle>
{
public GameObject[] cups = new GameObject[3]; // assign 3 GameObjects in Inspector
public int numberOfSwaps = 6; // how many swaps in the shuffle
public float swapDuration = 0.5f; // time per swap
public float arcHeight = 1.0f; // how high objects hop during swap
public float delayBetweenSwaps = 0.1f;
private Vector3[] positions = new Vector3[3]; // the 3 fixed slot positions
private int[] slotOccupant = new int[3]; // which cup index currently sits in slot i
public void StartShuffle()
{
cups = LevelLoader.Instance.Doors.ConvertAll((item) => item.gameObject).ToArray();
// Record starting positions as the 3 fixed slots
for (int i = 0; i < 3; i++)
{
positions[i] = cups[i].transform.position;
slotOccupant[i] = i; // cup i starts in slot i
}
StartCoroutine(ShuffleRoutine());
}
IEnumerator ShuffleRoutine()
{
for (int s = 0; s < numberOfSwaps; s++)
{
// Pick two different slots to swap
int slotA = Random.Range(0, 3);
int slotB;
do { slotB = Random.Range(0, 3); } while (slotB == slotA);
yield return StartCoroutine(SwapSlots(slotA, slotB));
yield return new WaitForSeconds(delayBetweenSwaps);
}
var sorted = cups.ToList();
sorted.Sort((a,b) => Mathf.RoundToInt(a.transform.position.x - b.transform.position.x));
sorted[0].GetComponent<DoorManager>().mod = "#LEFT";
sorted[1].GetComponent<DoorManager>().mod = "#CENTER";
sorted[2].GetComponent<DoorManager>().mod = "#RIGHT";
}
IEnumerator SwapSlots(int slotA, int slotB)
{
GameObject objA = cups[slotOccupant[slotA]];
GameObject objB = cups[slotOccupant[slotB]];
Vector3 startA = positions[slotA];
Vector3 startB = positions[slotB];
Vector3 endA = positions[slotB];
Vector3 endB = positions[slotA];
float t = 0f;
while (t < swapDuration)
{
t += Time.deltaTime;
float normalized = Mathf.Clamp01(t / swapDuration);
float ease = Mathf.SmoothStep(0f, 1f, normalized);
// Arc offset (sine curve peaks at the midpoint of the move)
float arc = Mathf.Sin(ease * Mathf.PI) * arcHeight;
objA.transform.position = Vector3.Lerp(startA, endA, ease) + Vector3.up * arc;
objB.transform.position = Vector3.Lerp(startB, endB, ease) + Vector3.up * arc;
yield return null;
}
// Snap to exact final positions
objA.transform.position = endA;
objB.transform.position = endB;
// Update which cup occupies which slot
int temp = slotOccupant[slotA];
slotOccupant[slotA] = slotOccupant[slotB];
slotOccupant[slotB] = temp;
}
}