Initial import of Rhyculator

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SahikandClaude Opus 5.5 committed 2026-10-24 11:55:22 +08:00
commit 728bb0c657
315 files changed
+96030

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
using UnityEngine;
using UnityEngine.UI;
using System;
public class AccountDisplay : MonoBehaviour
{
[Header("UI 元件")]
public Text UIDText;
public Text NameText;
public Text TypeText;
public Text CreateTimeText;
public Text EmailText;
public Text EmailVerifiedText;
public Text PhoneText;
public Text PhoneVerifiedText;
void Start()
{
ShowAccountInfo();
}
public void ShowAccountInfo()
{
int uid = PlayerPrefs.GetInt("UID", 0);
string name = PlayerPrefs.GetString("Name", "");
string type = PlayerPrefs.GetString("Type", "");
string createTime = PlayerPrefs.GetString("CreateTime", "");
string email = PlayerPrefs.GetString("Email", "");
bool emailVerified = PlayerPrefs.GetInt("EmailVerified", 0) == 1;
string phone = PlayerPrefs.GetString("Phone", "");
bool phoneVerified = PlayerPrefs.GetInt("PhoneVerified", 0) == 1;
string uidHex;
if (uid != 0 && !string.IsNullOrEmpty(type))
{
char typeChar = type switch
{
"R" => '0',
"A" => 'a',
"B" => 'b',
"D" => 'f',
_ => '?'
};
string uidHexPart = uid.ToString("X8");
uidHex = $"{typeChar}x{uidHexPart}";
}
else
{
uidHex = "0x00000000";
}
string typeDisplay = type;
switch (typeDisplay)
{
case "R": typeDisplay = "玩家"; break;
case "A": typeDisplay = "Alpha 測試"; break;
case "B": typeDisplay = "Beta 測試"; break;
case "D": typeDisplay = "開發者"; break;
}
// Email
string emailDisplay = "";
if (!string.IsNullOrEmpty(email) && email.Contains("@"))
{
int atIndex = email.IndexOf('@');
string prefix = email.Substring(0, Math.Min(2, atIndex));
string domain = email.Substring(atIndex);
emailDisplay = prefix + "*****" + domain;
}
// Phone
string phoneDisplay = "";
if (!string.IsNullOrEmpty(phone) && phone.Length >= 3)
{
string last3 = phone.Substring(phone.Length - 3);
phoneDisplay = new string('*', phone.Length - 3) + last3;
}
// Verified
string emailVerText = emailVerified ? "已驗證" : "未驗證";
string phoneVerText = phoneVerified ? "已驗證" : "未驗證";
// UI
UIDText.text = "使用者號碼: " + uidHex;
NameText.text = "顯示名稱: " + name;
TypeText.text = "帳號類型: " + typeDisplay;
CreateTimeText.text = "創建日期: " + createTime;
EmailText.text = "電子信箱: " + emailDisplay;
EmailVerifiedText.text = "狀態: " + emailVerText;
PhoneText.text = "電話號碼: " + phoneDisplay;
PhoneVerifiedText.text = "狀態: " + phoneVerText;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ac1f6dff7e49008498c23e6e0acffedc
+227
View File
@@ -0,0 +1,227 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
// 設定頁:音訊延遲校正
// 播放節拍聲,玩家只聽聲音跟著點擊;取偏差中位數存成 AudioOffsetMs
public class CalibrationController : MonoBehaviour
{
private const string SceneName = "SettingScene";
private const double Bpm = 100;
private const int BeatCount = 16;
private const int WarmupBeats = 4;
private const double LeadIn = 1.0;
private double Interval => 60.0 / Bpm;
private Font font;
private Text offsetText;
private Text statusText;
private Text beatText;
private Button startButton;
private AudioSource audioSource;
private AudioClip clickTrack;
private bool running;
private readonly List<double> deltas = new List<double>();
private readonly HashSet<int> ignoredTouches = new HashSet<int>();
// 進入設定頁時自動加入(不需改動場景)
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void Register()
{
SceneManager.sceneLoaded += (scene, mode) =>
{
if (scene.name == SceneName)
new GameObject("CalibrationController").AddComponent<CalibrationController>();
};
}
void Start()
{
// 沿用場景字型,並隱藏原本的佔位文字
foreach (var t in FindObjectsByType<Text>(FindObjectsSortMode.None))
{
if (font == null) font = t.font;
if (t.text.Trim() == "Empty") t.gameObject.SetActive(false);
}
EnhancedTouchSupport.Enable();
audioSource = gameObject.AddComponent<AudioSource>();
clickTrack = BuildClickTrack();
BuildUI();
RefreshOffset();
}
void OnDestroy()
{
if (running) SongClock.Stop();
}
void Update()
{
if (!running) return;
double now = SongClock.Now;
int beat = (int)System.Math.Floor((now - LeadIn) / Interval) + 1;
beatText.text = beat <= 0 ? "準備…" : $"{Mathf.Min(beat, BeatCount)} / {BeatCount}";
PollTaps(now);
if (now > LeadIn + (BeatCount - 0.5) * Interval + 0.3)
Finish();
}
void PollTaps(double now)
{
double real = Time.realtimeSinceStartupAsDouble;
foreach (var t in Touch.activeTouches)
{
if (t.phase != UnityEngine.InputSystem.TouchPhase.Began) continue;
if (ignoredTouches.Contains(t.touchId)) continue;
double age = System.Math.Min(0.1, System.Math.Max(0, real - t.startTime));
if (CalibrationMath.TryBeatDelta(now - age, LeadIn, Interval, BeatCount, WarmupBeats, out double d))
deltas.Add(d);
}
}
void StartCalibration()
{
deltas.Clear();
ignoredTouches.Clear();
// 開始前已按著的手指(按下「開始」的那一下)不計入
foreach (var t in Touch.activeTouches)
ignoredTouches.Add(t.touchId);
double dspStart = AudioSettings.dspTime + 0.2;
audioSource.clip = clickTrack;
audioSource.PlayScheduled(dspStart);
SongClock.Begin(dspStart, applyOffset: false);
running = true;
startButton.interactable = false;
statusText.text = "閉上眼睛,跟著聲音點擊螢幕任意處";
}
void Finish()
{
running = false;
SongClock.Stop();
audioSource.Stop();
startButton.interactable = true;
beatText.text = "";
int needed = (BeatCount - WarmupBeats) / 2;
if (deltas.Count < needed)
{
statusText.text = $"有效點擊太少({deltas.Count} 次),請再試一次";
return;
}
int ms = (int)System.Math.Round(CalibrationMath.Median(deltas) * 1000);
SetOffset(ms);
statusText.text = $"已套用:{deltas.Count} 次有效點擊,中位數 {ms:+0;-0;0} ms";
}
void SetOffset(int ms)
{
PlayerPrefs.SetInt(SongClock.OffsetPrefKey, Mathf.Clamp(ms, -500, 500));
PlayerPrefs.Save();
RefreshOffset();
}
void RefreshOffset()
{
int ms = PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0);
offsetText.text = $"目前延遲補償:{ms:+0;-0;0} ms";
}
// 產生整段節拍聲(每四拍第一拍較高音)
AudioClip BuildClickTrack()
{
int rate = AudioSettings.outputSampleRate;
double length = LeadIn + BeatCount * Interval + 0.5;
var data = new float[(int)(rate * length)];
int clickLen = (int)(rate * 0.04);
for (int b = 0; b < BeatCount; b++)
{
int start = (int)((LeadIn + b * Interval) * rate);
double freq = b % 4 == 0 ? 1760 : 1320;
for (int i = 0; i < clickLen && start + i < data.Length; i++)
{
double env = System.Math.Exp(-i / (rate * 0.008));
data[start + i] = (float)(System.Math.Sin(2 * System.Math.PI * freq * i / rate) * env * 0.8);
}
}
var clip = AudioClip.Create("CalibrationClicks", data.Length, 1, rate, false);
clip.SetData(data, 0);
return clip;
}
// ---------- UI ----------
void BuildUI()
{
Canvas canvas = FindAnyObjectByType<Canvas>();
Transform parent = canvas.transform;
AddText(parent, "延遲校正", 72, Color.white, 520);
AddText(parent, "戴上平常玩的耳機,按「開始」後\n只聽聲音、跟著節拍點擊螢幕\n前 4 拍為暖身不計分", 40, new Color(0.8f, 0.8f, 0.8f), 340);
offsetText = AddText(parent, "", 52, new Color(1f, 0.42f, 0.8f), 160);
beatText = AddText(parent, "", 96, Color.white, 0);
statusText = AddText(parent, "", 38, new Color(0.8f, 0.8f, 0.8f), -140);
startButton = AddButton(parent, "開始", new Vector2(0, -300), new Vector2(420, 120), StartCalibration);
AddButton(parent, "-5 ms", new Vector2(-300, -460), new Vector2(240, 100), () => SetOffset(PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0) - 5));
AddButton(parent, "重設", new Vector2(0, -460), new Vector2(240, 100), () => SetOffset(0));
AddButton(parent, "+5 ms", new Vector2(300, -460), new Vector2(240, 100), () => SetOffset(PlayerPrefs.GetInt(SongClock.OffsetPrefKey, 0) + 5));
AddText(parent, "正值 = 聲音比畫面晚(藍牙耳機通常為正)", 32, new Color(0.55f, 0.55f, 0.55f), -580);
AddText(parent, $"匯入曲包:用檔案管理員或瀏覽器開啟 .zip → 選擇 Rhyculator\n目前已匯入 {SongLibrary.Songs.Count} 首",
30, new Color(0.55f, 0.55f, 0.55f), -760);
}
Text AddText(Transform parent, string content, int size, Color color, float y)
{
var go = new GameObject("CalibText", typeof(RectTransform));
go.transform.SetParent(parent, false);
var text = go.AddComponent<Text>();
text.font = font;
text.text = content;
text.fontSize = size;
text.color = color;
text.alignment = TextAnchor.MiddleCenter;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.verticalOverflow = VerticalWrapMode.Overflow;
text.raycastTarget = false;
var rt = text.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.sizeDelta = new Vector2(1000, size * 1.5f);
rt.anchoredPosition = new Vector2(0, y);
return text;
}
Button AddButton(Transform parent, string label, Vector2 pos, Vector2 size, UnityEngine.Events.UnityAction onClick)
{
var go = new GameObject("CalibButton", typeof(RectTransform));
go.transform.SetParent(parent, false);
var img = go.AddComponent<Image>();
img.color = new Color(0.33f, 0.33f, 0.33f);
var btn = go.AddComponent<Button>();
btn.onClick.AddListener(onClick);
var rt = img.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.sizeDelta = size;
rt.anchoredPosition = pos;
var text = AddText(go.transform, label, 44, Color.white, 0);
text.rectTransform.sizeDelta = size;
return btn;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f3c820e04a29bb48b04cf0685fdf378
+25
View File
@@ -0,0 +1,25 @@
using System.Collections.Generic;
// 延遲校正的計算(純函式,方便測試)
public static class CalibrationMath
{
// 點擊時間對最近一拍的偏差;超出半拍或屬於暖身拍則回傳 false
public static bool TryBeatDelta(double tapTime, double firstBeat, double interval, int beatCount, int warmupBeats, out double delta)
{
delta = 0;
int i = (int)System.Math.Round((tapTime - firstBeat) / interval);
if (i < warmupBeats || i >= beatCount) return false;
delta = tapTime - (firstBeat + i * interval);
return System.Math.Abs(delta) < interval / 2;
}
// 中位數(比平均值不受誤觸影響)
public static double Median(List<double> values)
{
if (values == null || values.Count == 0) return 0;
var sorted = new List<double>(values);
sorted.Sort();
int n = sorted.Count;
return n % 2 == 1 ? sorted[n / 2] : (sorted[n / 2 - 1] + sorted[n / 2]) / 2;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 21855371daac8a148b883bb46c4b43ce
+80
View File
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.IO;
// 譜面展開後的一個事件(slide 的每一格各是一個事件)
public struct ChartEvent
{
public double hitTime; // 判定時間(秒,已含曲包的 offset)
public string type; // tap / hold / slide
public int x, y;
public int holdMs;
}
// 讀取 Maker 統一格式的譜面:
// {"format":1,"divisor":4,"notes":[{"t":1216,"lane":"L","type":"tap","pos":{"x":0,"y":3}}, ...]}
// lane / locked 是製譜用的欄位,遊戲忽略;沒有座標、座標超出格子、型別不認識的音符略過並計入 skipped
public static class ChartLoader
{
public const int Columns = 5;
public const int Rows = 6;
public static List<ChartEvent> LoadFile(string path, int offsetMs, out int skipped)
=> Parse(File.ReadAllText(path), offsetMs, out skipped);
public static List<ChartEvent> Parse(string json, int offsetMs, out int skipped)
{
skipped = 0;
var events = new List<ChartEvent>();
object root = MiniJson.Parse(json);
// 也接受只有 notes 陣列的檔案
var notes = MiniJson.AsList(root) ?? MiniJson.AsList(MiniJson.Get(MiniJson.AsObject(root), "notes"));
if (notes == null) throw new FormatException("譜面缺少 notes 陣列");
double offset = offsetMs / 1000.0;
foreach (var item in notes)
{
var n = MiniJson.AsObject(item);
if (n == null || !MiniJson.TryGetNumber(n, "t", out double tMs)) { skipped++; continue; }
string type = MiniJson.GetString(n, "type", "tap");
double t = tMs / 1000.0 + offset;
bool hasEnd = MiniJson.TryGetNumber(n, "end", out double endMs);
if (type == "slide")
{
var cells = new List<(int x, int y)>();
var path = MiniJson.AsList(MiniJson.Get(n, "path"));
if (path != null)
foreach (var p in path)
if (TryCell(MiniJson.AsObject(p), out int cx, out int cy)) cells.Add((cx, cy));
if (cells.Count == 0) { skipped++; continue; }
// 路徑的格子平均分布在 t ~ end:第一格在 t、最後一格在 end
double end = hasEnd ? endMs / 1000.0 + offset : t;
double interval = cells.Count > 1 ? (end - t) / (cells.Count - 1) : 0;
for (int i = 0; i < cells.Count; i++)
events.Add(new ChartEvent { hitTime = t + interval * i, type = "slide", x = cells[i].x, y = cells[i].y });
}
else if (type == "tap" || type == "hold")
{
if (!TryCell(MiniJson.AsObject(MiniJson.Get(n, "pos")), out int x, out int y)) { skipped++; continue; }
int holdMs = type == "hold" && hasEnd ? (int)Math.Max(0, endMs - tMs) : 0;
events.Add(new ChartEvent { hitTime = t, type = type, x = x, y = y, holdMs = holdMs });
}
else skipped++;
}
events.Sort((a, b) => a.hitTime.CompareTo(b.hitTime));
return events;
}
private static bool TryCell(Dictionary<string, object> pos, out int x, out int y)
{
x = y = 0;
if (pos == null) return false;
if (!MiniJson.TryGetNumber(pos, "x", out double dx) || !MiniJson.TryGetNumber(pos, "y", out double dy)) return false;
x = (int)dx;
y = (int)dy;
return x >= 0 && x < Columns && y >= 0 && y < Rows;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a41b742a3c95c084a8044f32b0692b89
+23
View File
@@ -0,0 +1,23 @@
using UnityEngine;
// 啟動時的全域設定
public static class GameBoot
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Init()
{
// 幀率上限 = 螢幕支援的最高更新率(120Hz 手機就跑 120)
// 注意:Android 上 targetFrameRate = -1 代表平台預設 30fps,不是無限制;
// 超過螢幕更新率的幀也看不到,只會增加耗電與發熱
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = Mathf.Max(60, MaxRefreshRate());
}
static int MaxRefreshRate()
{
double max = Screen.currentResolution.refreshRateRatio.value;
foreach (var r in Screen.resolutions)
if (r.refreshRateRatio.value > max) max = r.refreshRateRatio.value;
return Mathf.RoundToInt((float)max);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7dababac1cb210545a1edfa37c46bed1
+53
View File
@@ -0,0 +1,53 @@
using UnityEngine;
using UnityEngine.UI;
public class GridColor : MonoBehaviour
{
public Image cellImage;
public Sprite defaultSprite;
public Sprite whiteSprite;
public Sprite blueSprite;
public Sprite orangeSprite;
public Sprite redSprite;
public Sprite greenSprite;
public int cellX;
public int cellY;
public float flashDuration = 0.3f;
private float flashEnd;
private bool colored; // 目前顯示的是判定色(優先於按住時的白色)
void Awake()
{
if (cellImage == null) cellImage = GetComponent<Image>();
if (defaultSprite == null) defaultSprite = cellImage.sprite;
enabled = false; // 沒有閃爍時不跑 Update
}
// 按住提示:不覆蓋判定色
public void FlashWhite()
{
if (enabled && colored) return;
Flash(whiteSprite, false);
}
public void FlashBlue() => Flash(blueSprite, true);
public void FlashOrange() => Flash(orangeSprite, true);
public void FlashRed() => Flash(redSprite, true);
public void FlashGreen() => Flash(greenSprite, true);
private void Flash(Sprite sprite, bool isColor)
{
cellImage.sprite = sprite;
colored = isColor;
flashEnd = Time.time + flashDuration;
enabled = true;
}
void Update()
{
if (Time.time < flashEnd) return;
cellImage.sprite = defaultSprite;
enabled = false;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a576b5bf68358b645bc2d0793ba0dfb0
+138
View File
@@ -0,0 +1,138 @@
using UnityEngine;
using UnityEngine.UI;
// 單一格子的顯示:靜態圖示(選單)或音符
// 音符動畫完全由 SongClock 決定,保證在 hitTime 時縮放剛好為 1
public class GridDisplay : MonoBehaviour
{
public Image image;
// 音符在判定點前多久出現(秒)
public const double AppearLead = 0.5;
// 出現時的圓形填滿動畫長度
private const double FillDuration = 0.2;
// 判定點前後的縮放區間:0.5 → 1 → 1.5
private const double GrowHalf = 0.2;
public int cellX;
public int cellY;
// 音符超過判定時間仍未被按 → 通知(Miss)
public System.Action<GridDisplay, string> OnExpired;
private RectTransform rt;
private Vector2 basePos;
private Image.Type baseType;
private bool active = false;
private string currentNote = "None";
private int currentSec = 0;
private double hitTime;
void Awake()
{
if (image == null)
image = GetComponent<Image>();
rt = GetComponent<RectTransform>();
baseType = image.type;
enabled = false; // 沒有音符時不跑 Update
}
void Update()
{
if (!active) return;
double t = SongClock.Now - hitTime;
if (t > NoteJudge.BadWindow)
{
string note = currentNote;
Clear();
OnExpired?.Invoke(this, note);
return;
}
UpdateVisual(t);
}
public void ShowNote(Sprite sprite, string note, int sec, double noteHitTime)
{
// 同格還有未處理的音符:視為 Miss,避免音符無聲消失造成統計少算
if (active)
{
string old = currentNote;
Clear();
OnExpired?.Invoke(this, old);
}
basePos = rt.anchoredPosition;
currentNote = note;
currentSec = sec;
hitTime = noteHitTime;
active = true;
enabled = true;
image.sprite = sprite;
image.enabled = true;
image.type = Image.Type.Filled;
image.fillMethod = Image.FillMethod.Radial360;
image.fillOrigin = 2;
image.fillClockwise = true;
UpdateVisual(SongClock.Now - hitTime);
}
// t = 目前時間 - 判定時間
private void UpdateVisual(double t)
{
double sinceAppear = t + AppearLead;
float fill = (float)System.Math.Min(1.0, System.Math.Max(0.0, sinceAppear / FillDuration));
float scale = t < -GrowHalf ? 0.5f : (float)(1.0 + t / (2 * GrowHalf));
float alpha = scale > 1f ? Mathf.Clamp01(1f - (scale - 1f) / 0.5f) : 1f;
image.fillAmount = fill;
SetAlpha(alpha);
Vector2 size = rt.sizeDelta;
rt.localScale = Vector3.one * scale;
rt.anchoredPosition = basePos + (1f - scale) * size / 2f;
}
public void SetImage(Sprite sprite)
{
if (active) Clear();
image.sprite = sprite;
image.enabled = (sprite != null);
SetAlpha(1f);
}
public void Clear()
{
if (active)
{
rt.localScale = Vector3.one;
rt.anchoredPosition = basePos;
image.type = baseType;
image.fillAmount = 1f;
active = false;
enabled = false;
}
SetAlpha(1f);
currentSec = 0;
currentNote = "None";
image.sprite = null;
image.enabled = false;
}
public void SetAlpha(float a)
{
if (image == null) return;
Color c = image.color;
c.a = a;
image.color = c;
}
public bool HasNote() => active;
public string GetNote() => currentNote;
public int GetSec() => currentSec;
public double GetHitTime() => hitTime;
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d019d349bdba3bd4da6179077b905f3d
+172
View File
@@ -0,0 +1,172 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GridDisplaySpawner : MonoBehaviour
{
public GameObject displayPrefab;
public int rows = 6;
public int columns = 5;
public Sprite imgNoteTap;
public Sprite imgNoteHold;
public Sprite imgNoteSlide;
public GridDisplay[,] displayCells;
// 音符過期未被按(x, y, 音符種類)
public event System.Action<int, int, string> NoteExpired;
[Header("Base Layout Settings")]
public float baseWidth = 1080f;
public float cellBase = 180f;
public float spaceBase = 20f;
public float heightBase = 90f;
// 格子上的文字(例如選歌頁的難度數字)
private readonly Dictionary<(int, int), Text> labels = new Dictionary<(int, int), Text>();
private float cellSize;
void Awake()
{
float scale = Screen.width / baseWidth;
cellSize = cellBase * scale;
float spacing = spaceBase * scale;
float heightOffset = heightBase * scale;
displayCells = new GridDisplay[columns, rows];
RectTransform rt = GetComponent<RectTransform>();
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
rt.anchorMin = new Vector2(0.5f, 0f);
rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
float totalWidth = columns * cellSize + (columns - 1) * spacing;
float startX = -totalWidth / 2f;
float startY = heightOffset;
for (int i = 0; i < rows * columns; i++)
{
GameObject obj = Instantiate(displayPrefab, transform);
int x = i % columns;
int y = i / columns;
RectTransform cellRT = obj.GetComponent<RectTransform>();
cellRT.anchorMin = new Vector2(0f, 0f);
cellRT.anchorMax = new Vector2(0f, 0f);
cellRT.pivot = new Vector2(0f, 0f);
cellRT.sizeDelta = new Vector2(cellSize, cellSize);
float posX = startX + x * (cellSize + spacing);
float posY = startY + y * (cellSize + spacing);
cellRT.anchoredPosition = new Vector2(posX, posY);
GridDisplay cell = obj.GetComponent<GridDisplay>();
cell.cellX = x;
cell.cellY = y;
cell.OnExpired = (c, note) => NoteExpired?.Invoke(c.cellX, c.cellY, note);
displayCells[x, y] = cell;
}
}
public void SetImage(int x, int y, Sprite image)
{
if (!InBound(x, y)) return;
displayCells[x, y].SetImage(image);
}
public void Clear(int x, int y)
{
if (!InBound(x, y)) return;
displayCells[x, y].Clear();
RemoveLabel((x, y));
}
// 在格子上顯示文字;text 為 null 或空字串時移除
public void SetLabel(int x, int y, string text, Color color, float fontScale = 0.55f)
{
if (!InBound(x, y)) return;
var key = (x, y);
if (string.IsNullOrEmpty(text))
{
RemoveLabel(key);
return;
}
if (!labels.TryGetValue(key, out var label) || label == null)
{
var go = new GameObject("Label", typeof(RectTransform));
go.transform.SetParent(displayCells[x, y].transform, false);
label = go.AddComponent<Text>();
label.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
label.fontStyle = FontStyle.Bold;
label.alignment = TextAnchor.MiddleCenter;
label.horizontalOverflow = HorizontalWrapMode.Overflow;
label.verticalOverflow = VerticalWrapMode.Overflow;
label.raycastTarget = false;
var rt = label.rectTransform;
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = rt.offsetMax = Vector2.zero;
labels[key] = label;
}
label.text = text;
label.color = color;
label.fontSize = Mathf.Max(1, Mathf.RoundToInt(cellSize * fontScale));
}
private void RemoveLabel((int, int) key)
{
if (labels.TryGetValue(key, out var label) && label != null) Destroy(label.gameObject);
labels.Remove(key);
}
public void PlayNoteTap(int x, int y, double hitTime)
{
if (!InBound(x, y)) return;
displayCells[x, y].ShowNote(imgNoteTap, "Tap", 0, hitTime);
}
public void PlayNoteHold(int x, int y, int durationMs, double hitTime)
{
if (!InBound(x, y)) return;
displayCells[x, y].ShowNote(imgNoteHold, "Hold", durationMs, hitTime);
}
public void PlayNoteSlide(int x, int y, double hitTime)
{
if (!InBound(x, y)) return;
displayCells[x, y].ShowNote(imgNoteSlide, "Slide", 0, hitTime);
}
public bool HasNote(int x, int y)
{
return InBound(x, y) && displayCells[x, y].HasNote();
}
public double GetHitTime(int x, int y)
{
if (!InBound(x, y)) return 0;
return displayCells[x, y].GetHitTime();
}
public string GetCurrentNote(int x, int y)
{
if (!InBound(x, y)) return "None";
return displayCells[x, y].GetNote();
}
public int GetCurrentSec(int x, int y)
{
if (!InBound(x, y)) return 0;
return displayCells[x, y].GetSec();
}
private bool InBound(int x, int y)
{
return x >= 0 && y >= 0 && x < columns && y < rows;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ef37c6cacf7f78545a4093fdcb5c4826
+95
View File
@@ -0,0 +1,95 @@
using UnityEngine;
public class GridSpawner : MonoBehaviour
{
public GameObject cellPrefab;
public int rows = 6;
public int columns = 5;
public GridColor[,] gridCells;
// 用於由螢幕座標直接算出格子
private RectTransform container;
private Camera canvasCamera;
private Vector2 origin; // 格子 (0,0) 左下角,在 container 本地座標
private float cellSize;
private float step; // 格子大小 + 間距
void Start()
{
float baseWidth = 1080f;
float cellBase = 180f;
float spaceBase = 20f;
float heightBase = 90f;
float scale = Screen.width / baseWidth;
cellSize = cellBase * scale;
float spacing = spaceBase * scale;
float heightOffset = heightBase * scale;
gridCells = new GridColor[columns, rows];
RectTransform rt = GetComponent<RectTransform>();
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
container = rt;
step = cellSize + spacing;
Canvas canvas = GetComponentInParent<Canvas>();
if (canvas != null && canvas.rootCanvas.renderMode != RenderMode.ScreenSpaceOverlay)
canvasCamera = canvas.rootCanvas.worldCamera;
rt.anchorMin = new Vector2(0.5f, 0f);
rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
float totalWidth = columns * cellSize + (columns - 1) * spacing;
float startX = -totalWidth / 2f;
float startY = heightOffset;
for (int i = 0; i < rows * columns; i++)
{
GameObject cellObj = Instantiate(cellPrefab, transform);
int x = i % columns;
int y = i / columns;
RectTransform cellRT = cellObj.GetComponent<RectTransform>();
cellRT.anchorMin = new Vector2(0f, 0f);
cellRT.anchorMax = new Vector2(0f, 0f);
cellRT.pivot = new Vector2(0f, 0f);
cellRT.sizeDelta = new Vector2(cellSize, cellSize);
float posX = startX + x * (cellSize + spacing);
float posY = startY + y * (cellSize + spacing);
cellRT.anchoredPosition = new Vector2(posX, posY);
GridColor cellColor = cellObj.GetComponent<GridColor>();
cellColor.cellX = x;
cellColor.cellY = y;
gridCells[x, y] = cellColor;
}
origin = gridCells[0, 0].transform.localPosition;
}
// 螢幕座標 → 格子座標;在格子外(含間距)回傳 false,x/y = -1
public bool CellAt(Vector2 screenPos, out int x, out int y)
{
x = y = -1;
if (gridCells == null) return false;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(container, screenPos, canvasCamera, out Vector2 local))
return false;
Vector2 p = local - origin;
int cx = Mathf.FloorToInt(p.x / step);
int cy = Mathf.FloorToInt(p.y / step);
if (cx < 0 || cy < 0 || cx >= columns || cy >= rows) return false;
if (p.x - cx * step > cellSize || p.y - cy * step > cellSize) return false;
x = cx;
y = cy;
return true;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1ebf2c7c1d748884d99b72572feb9ffe
+86
View File
@@ -0,0 +1,86 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using TouchPhase = UnityEngine.InputSystem.TouchPhase;
// 一根手指在本幀的狀態
public struct GridTouch
{
public int fingerId;
public Vector2 position;
public bool began; // 本幀新按下
public bool ended; // 本幀放開 / 取消
public int x, y; // 所在格子,不在格子上為 -1
public double pressAge; // 按下事件距今幾秒(用來回推精確的按下時間)
public bool OnCell => x >= 0;
}
// 格子場景共用的觸控輸入(EnhancedTouch:同一幀內按下又放開的快速點擊也不會漏掉)
// - 場景開始前就按著的手指會被忽略
// - 按下時若最上層是面板等 UI,這根手指直到放開都不會送到格子(防穿透)
// - 以排列規則直接算出格子座標,不必逐格判斷
public class GridTouchInput
{
private readonly GridSpawner grid;
private readonly List<Transform> gridRoots = new List<Transform>();
private readonly HashSet<int> ignored = new HashSet<int>();
private readonly List<GridTouch> touches = new List<GridTouch>();
// 按下事件最多回推的秒數(避免掉幀時判定被推太遠)
private const double MaxPressAge = 0.1;
public GridTouchInput(GridSpawner grid, params Component[] gridParts)
{
EnhancedTouchSupport.Enable();
this.grid = grid;
foreach (var part in gridParts)
if (part != null) gridRoots.Add(part.transform);
}
// 場景開始時呼叫:忽略已經按著的手指
public void IgnoreCurrentTouches()
{
foreach (var t in Touch.activeTouches)
ignored.Add(t.touchId);
}
public List<GridTouch> Poll()
{
touches.Clear();
if (grid == null || grid.gridCells == null) return touches;
double now = Time.realtimeSinceStartupAsDouble;
foreach (var t in Touch.activeTouches)
{
int id = t.touchId;
TouchPhase phase = t.phase;
bool ended = phase == TouchPhase.Ended || phase == TouchPhase.Canceled;
bool began = phase == TouchPhase.Began;
if (began && UIHitTest.IsBlocked(t.screenPosition, gridRoots))
ignored.Add(id);
if (ignored.Contains(id))
{
if (ended) ignored.Remove(id);
continue;
}
Vector2 pos = t.screenPosition;
if (ended)
{
touches.Add(new GridTouch { fingerId = id, ended = true, x = -1, y = -1, position = pos });
continue;
}
grid.CellAt(pos, out int x, out int y);
double age = began ? System.Math.Min(MaxPressAge, System.Math.Max(0, now - t.startTime)) : 0;
touches.Add(new GridTouch { fingerId = id, position = pos, began = began, x = x, y = y, pressAge = age });
}
return touches;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 58c9f43e3bbee1041b9972c39d2cf5cb
+59
View File
@@ -0,0 +1,59 @@
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HoldProgress : MonoBehaviour
{
public Image radialImage;
private Coroutine progressCoroutine;
void Awake()
{
if (radialImage != null)
{
radialImage.fillAmount = 0f;
radialImage.gameObject.SetActive(false);
}
}
// 開始
public void StartProgress(float seconds)
{
if (radialImage == null || seconds <= 0f) return;
if (progressCoroutine != null)
StopCoroutine(progressCoroutine);
radialImage.gameObject.SetActive(true);
progressCoroutine = StartCoroutine(ProgressCoroutine(seconds));
}
// 中斷
public void StopProgress()
{
if (progressCoroutine != null)
{
StopCoroutine(progressCoroutine);
progressCoroutine = null;
}
if (radialImage != null)
{
radialImage.fillAmount = 0f;
radialImage.gameObject.SetActive(false);
}
}
private IEnumerator ProgressCoroutine(float seconds)
{
float elapsed = 0f;
while (elapsed < seconds)
{
elapsed += Time.deltaTime;
radialImage.fillAmount = 1f - Mathf.Clamp01(elapsed / seconds);
yield return null;
}
radialImage.fillAmount = 0f;
radialImage.gameObject.SetActive(false);
progressCoroutine = null;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1c186d43719e3604eb17df884c7aa488
+80
View File
@@ -0,0 +1,80 @@
using UnityEngine;
public class HoldHintSpawner : MonoBehaviour
{
public GameObject holdProgressPrefab;
public int rows = 6;
public int columns = 5;
public float baseWidth = 1080f;
public float cellBase = 180f;
public float spaceBase = 20f;
public float heightBase = 90f;
public HoldProgress[,] holdProgressArray;
public Vector2 offset = new Vector2(-60f, 60f);
public Vector2 prefabSize = new Vector2(300f, 300f);
void Start()
{
float scale = Screen.width / baseWidth;
float cellSize = cellBase * scale;
float spacing = spaceBase * scale;
float heightOffset = heightBase * scale;
holdProgressArray = new HoldProgress[columns, rows];
RectTransform rt = GetComponent<RectTransform>();
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
rt.anchorMin = new Vector2(0.5f, 0f);
rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
float totalWidth = columns * cellSize + (columns - 1) * spacing;
float startX = -totalWidth / 2f;
float startY = heightOffset;
Vector2[,] positions = new Vector2[columns, rows];
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
float posX = startX + x * (cellSize + spacing) + offset.x;
float posY = startY + y * (cellSize + spacing) + offset.y;
positions[x, y] = new Vector2(posX, posY);
}
}
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
GameObject obj = Instantiate(holdProgressPrefab, transform);
RectTransform objRT = obj.GetComponent<RectTransform>();
objRT.anchorMin = new Vector2(0f, 0f);
objRT.anchorMax = new Vector2(0f, 0f);
objRT.pivot = new Vector2(0f, 0f);
objRT.sizeDelta = prefabSize;
objRT.anchoredPosition = positions[x, y];
HoldProgress progress = obj.GetComponent<HoldProgress>();
holdProgressArray[x, y] = progress;
}
}
}
public void StartProgressAt(int x, int y, float seconds)
{
if (x < 0 || y < 0 || x >= columns || y >= rows) return;
HoldProgress progress = holdProgressArray[x, y];
progress?.StartProgress(seconds);
}
public void StopProgressAt(int x, int y)
{
if (x < 0 || y < 0 || x >= columns || y >= rows) return;
HoldProgress progress = holdProgressArray[x, y];
progress?.StopProgress();
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a1e5722644910a4bb03d9bbec945c81
+35
View File
@@ -0,0 +1,35 @@
using UnityEngine;
using UnityEngine.UI;
public class MarqueeText : MonoBehaviour
{
public float speed = 50f;
public float resetOffset = 500f;
public float waitTime = 1.0f;
private RectTransform rect;
private float waitTimer = 0f;
void Start()
{
rect = GetComponent<RectTransform>();
}
void Update()
{
if (waitTimer > 0f)
{
waitTimer -= Time.deltaTime;
return;
}
rect.anchoredPosition += Vector2.left * speed * Time.deltaTime;
if (rect.anchoredPosition.x <= -resetOffset)
{
rect.anchoredPosition = new Vector2(resetOffset, rect.anchoredPosition.y);
waitTimer = waitTime;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 636822f2903e8b64c94b218d9497a24e
+175
View File
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
// 精簡 JSON 讀取器:物件 → Dictionary<string, object>、陣列 → List<object>、
// 數字 → double、字串 → string、true/false → bool、null → null
// 曲包譜面的 pos / path / end / locked 都是「可有可無」的欄位,JsonUtility 會把缺少的巢狀物件
// 填成預設值,分不出「沒有座標」和「座標 (0,0)」,所以自己解析
public static class MiniJson
{
public static object Parse(string json)
{
if (json == null) throw new FormatException("JSON 為空");
var p = new Parser(json);
p.SkipWhitespace();
object v = p.ParseValue();
p.SkipWhitespace();
if (!p.AtEnd) throw p.Error("結尾有多餘的內容");
return v;
}
public static Dictionary<string, object> AsObject(object v) => v as Dictionary<string, object>;
public static List<object> AsList(object v) => v as List<object>;
public static object Get(Dictionary<string, object> obj, string key)
=> obj != null && obj.TryGetValue(key, out var v) ? v : null;
public static string GetString(Dictionary<string, object> obj, string key, string fallback = null)
=> Get(obj, key) is string s ? s : fallback;
public static bool TryGetNumber(Dictionary<string, object> obj, string key, out double value)
{
if (Get(obj, key) is double d) { value = d; return true; }
value = 0;
return false;
}
public static double GetNumber(Dictionary<string, object> obj, string key, double fallback = 0)
=> TryGetNumber(obj, key, out var d) ? d : fallback;
public static int GetInt(Dictionary<string, object> obj, string key, int fallback = 0)
=> TryGetNumber(obj, key, out var d) ? (int)Math.Round(d) : fallback;
public static bool GetBool(Dictionary<string, object> obj, string key, bool fallback = false)
=> Get(obj, key) is bool b ? b : fallback;
private class Parser
{
private readonly string s;
private int i;
public Parser(string s) { this.s = s; }
public bool AtEnd => i >= s.Length;
public FormatException Error(string msg) => new FormatException($"JSON 第 {i} 個字元:{msg}");
public void SkipWhitespace()
{
while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
}
public object ParseValue()
{
if (AtEnd) throw Error("內容不完整");
char c = s[i];
switch (c)
{
case '{': return ParseObject();
case '[': return ParseArray();
case '"': return ParseString();
case 't': Expect("true"); return true;
case 'f': Expect("false"); return false;
case 'n': Expect("null"); return null;
default:
if (c == '-' || (c >= '0' && c <= '9')) return ParseNumber();
throw Error($"無法解析 '{c}'");
}
}
private void Expect(string word)
{
if (string.CompareOrdinal(s, i, word, 0, word.Length) != 0) throw Error($"預期 {word}");
i += word.Length;
}
private Dictionary<string, object> ParseObject()
{
var obj = new Dictionary<string, object>();
i++; // {
SkipWhitespace();
if (i < s.Length && s[i] == '}') { i++; return obj; }
while (true)
{
SkipWhitespace();
if (AtEnd || s[i] != '"') throw Error("物件的鍵必須是字串");
string key = ParseString();
SkipWhitespace();
if (AtEnd || s[i] != ':') throw Error("缺少 ':'");
i++;
SkipWhitespace();
obj[key] = ParseValue();
SkipWhitespace();
if (AtEnd) throw Error("物件未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == '}') { i++; return obj; }
throw Error("物件內預期 ',' 或 '}'");
}
}
private List<object> ParseArray()
{
var list = new List<object>();
i++; // [
SkipWhitespace();
if (i < s.Length && s[i] == ']') { i++; return list; }
while (true)
{
SkipWhitespace();
list.Add(ParseValue());
SkipWhitespace();
if (AtEnd) throw Error("陣列未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == ']') { i++; return list; }
throw Error("陣列內預期 ',' 或 ']'");
}
}
private string ParseString()
{
i++; // 開頭的引號
var sb = new StringBuilder();
while (true)
{
if (AtEnd) throw Error("字串未結束");
char c = s[i++];
if (c == '"') return sb.ToString();
if (c != '\\') { sb.Append(c); continue; }
if (AtEnd) throw Error("字串未結束");
char e = s[i++];
switch (e)
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
if (i + 4 > s.Length) throw Error("\\u 跳脫不完整");
sb.Append((char)int.Parse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
i += 4;
break;
default: throw Error($"不支援的跳脫 \\{e}");
}
}
}
private double ParseNumber()
{
int start = i;
if (s[i] == '-') i++;
while (i < s.Length && IsNumberChar(s[i])) i++;
string token = s.Substring(start, i - start);
if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
throw Error($"數字格式錯誤 '{token}'");
return d;
}
private static bool IsNumberChar(char c)
=> (c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-';
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 756aef3f2685f5641bfea1d649343619
+217
View File
@@ -0,0 +1,217 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Video;
// 播放音樂並依 SongClock 生成音符
// 音樂用 PlayScheduled 排在 DSP 時鐘上,音符時間與音訊同一個時間基準,不會累積誤差
// 在 GridDisplay(過期判定)之後才生成新音符,掉幀時也不會先蓋掉同格未結算的音符
//
// 兩種模式:
// - menuSheet 有指定(主畫面):用內建的背景譜面,音樂由 AudioSource 的 Play On Awake 播放
// - menuSheet 留空(遊玩):載入 SongLibrary.Current 這個曲包的音樂、譜面與影片
[DefaultExecutionOrder(100)]
public class MusicPlayer : MonoBehaviour
{
public AudioSource audioSource;
public GridDisplaySpawner gridDisplaySpawner;
[Tooltip("主畫面的內建背景譜面;留空時載入目前選擇的曲包")]
public TextAsset menuSheet;
// 音樂開始前的準備時間,讓開頭的音符也有完整的出現動畫
public float leadInSec = 1.0f;
// 曲包影片的透明度(0 = 不顯示影片)
[Range(0f, 1f)] public float videoAlpha = 0.4f;
public SongInfo Song { get; private set; }
public int Level { get; private set; }
public bool Ready { get; private set; }
public string Error { get; private set; }
public int TotalNotes => events.Count;
public int SkippedNotes { get; private set; }
private readonly List<ChartEvent> events = new List<ChartEvent>();
private int nextEvent = 0;
private AudioClip loadedClip;
private VideoPlayer video;
private bool videoStarted;
// 歌曲(含結尾緩衝)是否已結束
public bool Finished =>
Ready && SongClock.Running && audioSource.clip != null &&
SongClock.Now > audioSource.clip.length + NoteJudge.BadWindow + 0.5;
void Start()
{
if (menuSheet != null) StartMenu();
else StartCoroutine(LoadAndPlaySong());
}
void OnDestroy()
{
SongClock.Stop();
if (audioSource != null) audioSource.Stop();
if (loadedClip != null)
{
if (audioSource != null) audioSource.clip = null;
Destroy(loadedClip);
}
}
// 主畫面:音樂已由 Play On Awake 開始播放,時鐘對齊目前播放位置
void StartMenu()
{
try
{
SetEvents(ChartLoader.Parse(menuSheet.text, 0, out int skipped));
SkippedNotes = skipped;
}
catch (Exception e)
{
Debug.LogError("[MusicPlayer] 主畫面譜面讀取失敗:" + e.Message);
}
double dspStart;
if (audioSource.isPlaying)
{
dspStart = AudioSettings.dspTime - audioSource.time;
}
else
{
dspStart = AudioSettings.dspTime + leadInSec;
audioSource.PlayScheduled(dspStart);
}
SongClock.Begin(dspStart);
Ready = true;
}
IEnumerator LoadAndPlaySong()
{
Song = SongLibrary.Current;
Level = PlayerPrefs.GetInt("NowPlayingLevel", 1);
if (Song == null) { Fail("沒有選擇曲目"); yield break; }
if (!Song.HasLevel(Level)) Level = Song.FirstLevel();
if (Level == 0) { Fail("這個曲包沒有譜面"); yield break; }
try
{
SetEvents(ChartLoader.LoadFile(Song.ChartPath(Level), Song.offsetMs, out int skipped));
SkippedNotes = skipped;
}
catch (Exception e)
{
Fail("譜面讀取失敗:" + e.Message);
yield break;
}
string musicPath = Song.MusicPath;
if (musicPath == null) { Fail("曲包沒有音樂"); yield break; }
using (var www = LoadAudio(musicPath))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Fail("音樂載入失敗:" + www.error);
yield break;
}
loadedClip = DownloadHandlerAudioClip.GetContent(www);
}
if (loadedClip == null || loadedClip.length <= 0f) { Fail("音樂無法解碼"); yield break; }
audioSource.clip = loadedClip;
if (videoAlpha > 0f && Song.VideoPath != null) SetupVideo(Song.VideoPath);
double start = AudioSettings.dspTime + leadInSec;
audioSource.PlayScheduled(start);
SongClock.Begin(start);
Ready = true;
Debug.Log($"[MusicPlayer] {Song.id} {SongInfo.LevelName(Level)}: {events.Count} events, skipped {SkippedNotes}, clip {loadedClip.length:0.0}s");
}
void Fail(string message)
{
Error = message;
Debug.LogError("[MusicPlayer] " + message);
}
void SetEvents(List<ChartEvent> list)
{
events.Clear();
events.AddRange(list);
nextEvent = 0;
}
// 本機檔案 → UnityWebRequest 用的 file:// 網址(處理空白與 Windows 路徑)
public static string FileUrl(string path) => new Uri(Path.GetFullPath(path)).AbsoluteUri;
// 載入曲包音樂:ogg / mp3 保持壓縮(整首不解壓,省記憶體);
// wav 本來就是 PCM,開壓縮模式在 Android 上會讓主執行緒卡死,所以直接載入
public static UnityWebRequest LoadAudio(string path)
{
AudioType type = AudioTypeOf(path);
var www = UnityWebRequestMultimedia.GetAudioClip(FileUrl(path), type);
((DownloadHandlerAudioClip)www.downloadHandler).compressed = type != AudioType.WAV;
return www;
}
public static AudioType AudioTypeOf(string path)
{
switch (Path.GetExtension(path).ToLowerInvariant())
{
case ".ogg": return AudioType.OGGVORBIS;
case ".mp3": return AudioType.MPEG;
default: return AudioType.WAV;
}
}
// 曲包的 video.mp4:畫在攝影機最後方當背景,聲音一律用 music 檔
void SetupVideo(string path)
{
Camera cam = Camera.main;
if (cam == null) return;
var go = new GameObject("PackVideo");
video = go.AddComponent<VideoPlayer>();
video.playOnAwake = false;
video.source = VideoSource.Url;
video.url = path;
video.renderMode = VideoRenderMode.CameraFarPlane;
video.targetCamera = cam;
video.targetCameraAlpha = videoAlpha;
video.aspectRatio = VideoAspectRatio.FitOutside;
video.audioOutputMode = VideoAudioOutputMode.None;
video.isLooping = false;
video.skipOnDrop = true;
video.Prepare();
}
void Update()
{
if (!Ready || !SongClock.Running) return;
double now = SongClock.Now;
if (video != null && !videoStarted && now >= 0 && video.isPrepared)
{
if (now > 0.05) video.time = now; // 準備得比音樂慢:從目前位置接上
video.Play();
videoStarted = true;
}
double spawnUntil = now + GridDisplay.AppearLead;
while (nextEvent < events.Count && events[nextEvent].hitTime <= spawnUntil)
{
var e = events[nextEvent++];
switch (e.type)
{
case "tap": gridDisplaySpawner.PlayNoteTap(e.x, e.y, e.hitTime); break;
case "hold": gridDisplaySpawner.PlayNoteHold(e.x, e.y, e.holdMs, e.hitTime); break;
case "slide": gridDisplaySpawner.PlayNoteSlide(e.x, e.y, e.hitTime); break;
}
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b1550e937dea5d848b86814da8b1cc4e
+39
View File
@@ -0,0 +1,39 @@
// 判定:以「按下時間 - 音符時間」決定結果(秒)
// 時間窗沿用舊版以動畫縮放判定時的手感:Perfect ±50ms、Fast/Slow ±130ms、Bad ±200ms
public enum Judgement
{
None, // 不在判定範圍內(太早),不處理
Perfect,
Fast,
Slow,
Bad,
Miss // 音符過期沒按到
}
public static class NoteJudge
{
public const double PerfectWindow = 0.050;
public const double GreatWindow = 0.130;
public const double BadWindow = 0.200;
public static Judgement Evaluate(double delta)
{
double abs = System.Math.Abs(delta);
if (abs <= PerfectWindow) return Judgement.Perfect;
if (abs <= GreatWindow) return delta < 0 ? Judgement.Fast : Judgement.Slow;
if (abs <= BadWindow) return Judgement.Bad;
return delta > 0 ? Judgement.Miss : Judgement.None;
}
public static int Score(Judgement j)
{
switch (j)
{
case Judgement.Perfect: return 212;
case Judgement.Fast:
case Judgement.Slow: return 159;
case Judgement.Bad: return 53;
default: return 0;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f85fc10a56e03644bb72ae9bbecbc66d
+67
View File
@@ -0,0 +1,67 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
// 檢查收件匣(persistentDataPath 根目錄)裡的曲包 zip 並匯入:
// - Android:用檔案管理員「開啟」或「分享」給本 app 的 zip,由 RhyculatorActivity.java 複製到收件匣
// - 也可以直接把 zip 放進收件匣(adb push、檔案管理員複製)
// C# 端不呼叫 Java,只看檔案;開啟遊戲、回到前景時立即檢查,之後每秒檢查一次
public class PackImportWatcher : MonoBehaviour
{
private float nextCheck;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Init()
{
var go = new GameObject("PackImportWatcher");
DontDestroyOnLoad(go);
go.AddComponent<PackImportWatcher>();
}
void OnApplicationFocus(bool focus)
{
if (focus) nextCheck = 0f;
}
void Update()
{
if (Time.unscaledTime < nextCheck) return;
nextCheck = Time.unscaledTime + 1f;
Check();
}
void Check()
{
var errors = new List<string>();
ReadReceiveError(errors);
var imported = PackImporter.ImportInbox(errors);
if (imported.Count == 0 && errors.Count == 0) return;
SongLibrary.Reload();
foreach (var e in errors) Toast.Show("匯入失敗:" + e);
if (imported.Count == 0) return;
SongLibrary.Current = SongLibrary.Find(imported[imported.Count - 1].id);
Toast.Show(imported.Count == 1 ? $"已匯入「{imported[0].name}」" : $"已匯入 {imported.Count} 個曲包");
// 遊玩中不打斷;其他畫面直接跳到選歌
if (SceneManager.GetActiveScene().name != "PlayingScene")
SceneManager.LoadScene("ChooseScene");
}
// Java 端讀取 content URI 失敗時留下的訊息
static void ReadReceiveError(List<string> errors)
{
string path = Path.Combine(SongLibrary.InboxDir, SongLibrary.ImportErrorFile);
if (!File.Exists(path)) return;
string detail = "";
try { detail = File.ReadAllText(path); } catch { }
try { File.Delete(path); } catch { }
Debug.LogWarning("[PackImport] " + detail);
errors.Add(detail.Contains("Permission Denial") || detail.Contains("SecurityException")
? "沒有讀取這個檔案的權限,請從檔案管理員用「開啟」或「分享」送給 Rhyculator"
: "無法讀取檔案");
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 54e39548d739d76479a8a7fad634cb34
+119
View File
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
// 曲包(.zip)匯入:檢查內容 → 解壓到 songs/<id>/(同 id 的舊曲包會被覆蓋)
public static class PackImporter
{
public class ImportException : Exception
{
public ImportException(string message) : base(message) { }
}
// 只解出這些檔名;zip 內其他東西一律忽略(也避免 zip 內的路徑寫到別處)
private static readonly HashSet<string> Allowed = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
SongInfo.ConfigName, SongInfo.ImageName, SongInfo.VideoName,
"easy.json", "normal.json", "hard.json",
"music.ogg", "music.wav", "music.mp3",
};
private const long MaxEntryBytes = 512L * 1024 * 1024;
public static SongInfo Import(string zipPath)
{
using var fs = File.OpenRead(zipPath);
return Import(fs);
}
public static SongInfo Import(Stream zipStream)
{
using var zip = new ZipArchive(zipStream, ZipArchiveMode.Read, leaveOpen: true);
// 允許整個資料夾被壓進去(檔案都在同一層子資料夾):以最淺的 config.json 所在位置為根
ZipArchiveEntry config = null;
foreach (var e in zip.Entries)
{
if (!string.Equals(e.Name, SongInfo.ConfigName, StringComparison.OrdinalIgnoreCase)) continue;
if (config == null || e.FullName.Length < config.FullName.Length) config = e;
}
if (config == null) throw new ImportException("zip 裡沒有 config.json,不是曲包");
string prefix = config.FullName.Substring(0, config.FullName.Length - config.Name.Length);
var files = new Dictionary<string, ZipArchiveEntry>();
foreach (var e in zip.Entries)
{
if (!e.FullName.StartsWith(prefix, StringComparison.Ordinal)) continue;
string rel = e.FullName.Substring(prefix.Length);
if (rel.Length == 0 || rel.IndexOf('/') >= 0 || rel.IndexOf('\\') >= 0) continue; // 目錄項目、子資料夾
if (!Allowed.Contains(rel)) continue;
if (e.Length > MaxEntryBytes) throw new ImportException($"{rel} 太大");
files[rel.ToLowerInvariant()] = e;
}
string configText;
using (var reader = new StreamReader(config.Open(), System.Text.Encoding.UTF8))
configText = reader.ReadToEnd();
SongInfo info;
try { info = SongInfo.FromConfig(configText, null); }
catch (FormatException e) { throw new ImportException(e.Message); }
bool hasChart = false;
foreach (var n in SongInfo.LevelNames) if (files.ContainsKey(n + ".json")) hasChart = true;
if (!hasChart) throw new ImportException("曲包沒有任何難度的譜面");
bool hasMusic = false;
foreach (var n in SongInfo.MusicNames) if (files.ContainsKey(n)) hasMusic = true;
if (!hasMusic) throw new ImportException("曲包沒有音樂(music.ogg / wav / mp3)");
if (!files.ContainsKey(SongInfo.ImageName)) throw new ImportException("曲包沒有封面 image.png");
// 先解到暫存資料夾,全部成功才取代舊的
string root = SongLibrary.RootDir;
Directory.CreateDirectory(root);
string final = Path.Combine(root, info.id);
string temp = Path.Combine(root, info.id + ".importing");
if (Directory.Exists(temp)) Directory.Delete(temp, true);
Directory.CreateDirectory(temp);
try
{
foreach (var kv in files)
{
using var src = kv.Value.Open();
using var dst = File.Create(Path.Combine(temp, kv.Key));
src.CopyTo(dst);
}
if (Directory.Exists(final)) Directory.Delete(final, true);
Directory.Move(temp, final);
}
catch
{
if (Directory.Exists(temp)) Directory.Delete(temp, true);
throw;
}
return SongInfo.FromDir(final);
}
// 匯入收件匣裡的所有 *.zip;不論成功失敗都會刪掉 zip,避免每次開啟都重試
public static List<SongInfo> ImportInbox(List<string> errors)
{
var imported = new List<SongInfo>();
string inbox = SongLibrary.InboxDir;
if (!Directory.Exists(inbox)) return imported;
foreach (var zip in Directory.GetFiles(inbox, "*.zip"))
{
try { imported.Add(Import(zip)); }
catch (Exception e) { errors.Add($"{Path.GetFileName(zip)}:{Describe(e)}"); }
try { File.Delete(zip); } catch { }
}
return imported;
}
// 給玩家看的錯誤訊息
public static string Describe(Exception e)
{
if (e is ImportException || e is FormatException) return e.Message;
if (e is InvalidDataException) return "不是有效的 zip 檔";
return e.GetType().Name + ": " + e.Message;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c0876d2a8cc58b346b9007f5ca830a23
+30
View File
@@ -0,0 +1,30 @@
// 一次遊玩的統計,給結算/上傳使用
public class PlayResult
{
public int score;
public int perfect, fast, slow, bad, miss;
public int maxCombo;
public int combo;
public static PlayResult Last { get; set; }
public void Add(Judgement j, int points)
{
score += points;
switch (j)
{
case Judgement.Perfect: perfect++; break;
case Judgement.Fast: fast++; break;
case Judgement.Slow: slow++; break;
case Judgement.Bad: bad++; break;
case Judgement.Miss: miss++; break;
}
if (j == Judgement.Miss) combo = 0;
else if (j != Judgement.None) combo++;
if (combo > maxCombo) maxCombo = combo;
}
public override string ToString() =>
$"score={score} P={perfect} F={fast} S={slow} B={bad} M={miss} maxCombo={maxCombo}";
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 48d770f32e4d63d48ac02109441a84af
+87
View File
@@ -0,0 +1,87 @@
using UnityEngine;
using UnityEngine.UI;
// 結算畫面(以程式建立,不需改動場景)
public static class ResultOverlay
{
public static GameObject Show(PlayResult r, int totalNotes, Font font, string uploadStatus)
{
var root = new GameObject("ResultOverlay", typeof(Canvas), typeof(CanvasScaler));
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 100;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 2400);
scaler.matchWidthOrHeight = 0f;
var bg = NewChild(root.transform, "Background").AddComponent<Image>();
bg.color = new Color(0f, 0f, 0f, 0.88f);
Stretch(bg.rectTransform);
int hit = r.perfect + r.fast + r.slow + r.bad;
float acc = totalNotes > 0
? (r.perfect + 0.75f * (r.fast + r.slow) + 0.25f * r.bad) / totalNotes * 100f
: 0f;
AddText(root.transform, font, "RESULT", 72, new Color(1f, 0.42f, 0.8f), 600);
AddText(root.transform, font, r.score.ToString(), 140, Color.white, 420);
AddText(root.transform, font, $"準確率 {acc:0.00}% 最大連擊 {r.maxCombo}", 44, new Color(0.85f, 0.85f, 0.85f), 280);
// 兩欄:判定名稱靠右、次數靠左(比例字型無法用空白對齊)
string names =
"<color=#6EB4FF>Perfect</color>\n<color=#7CD67C>Fast</color>\n<color=#FFA64D>Slow</color>\n" +
"<color=#FF5050>Bad</color>\n<color=#888888>Miss</color>";
string counts = $"{r.perfect}\n{r.fast}\n{r.slow}\n{r.bad}\n{r.miss}";
AddColumn(root.transform, font, names, TextAnchor.MiddleRight, -40);
AddColumn(root.transform, font, counts, TextAnchor.MiddleLeft, 40);
AddText(root.transform, font, uploadStatus, 36, new Color(0.6f, 0.6f, 0.6f), -330);
AddText(root.transform, font, "點擊任意處繼續", 44, new Color(0.85f, 0.85f, 0.85f), -520);
return root;
}
private static void AddColumn(Transform parent, Font font, string content, TextAnchor align, float x)
{
var text = AddText(parent, font, content, 56, Color.white, 0);
text.supportRichText = true;
text.alignment = align;
text.lineSpacing = 1.1f;
var rt = text.rectTransform;
rt.pivot = new Vector2(align == TextAnchor.MiddleRight ? 1f : 0f, 0.5f);
rt.sizeDelta = new Vector2(400, 440);
rt.anchoredPosition = new Vector2(x, 0);
}
private static GameObject NewChild(Transform parent, string name)
{
var go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
return go;
}
private static void Stretch(RectTransform rt)
{
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = rt.offsetMax = Vector2.zero;
}
private static Text AddText(Transform parent, Font font, string content, int size, Color color, float y)
{
var text = NewChild(parent, "Text").AddComponent<Text>();
text.font = font;
text.text = content;
text.fontSize = size;
text.color = color;
text.alignment = TextAnchor.MiddleCenter;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
text.verticalOverflow = VerticalWrapMode.Overflow;
text.raycastTarget = false;
var rt = text.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.sizeDelta = new Vector2(1000, size * 1.5f);
rt.anchoredPosition = new Vector2(0, y);
return text;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 31af18566e9d68a4cbebbad7400e4329
+18
View File
@@ -0,0 +1,18 @@
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ReturnToMain : MonoBehaviour
{
public Button returnButton;
void Start()
{
returnButton.onClick.AddListener(ReturnMain);
}
void ReturnMain()
{
SceneManager.LoadScene("MainScene");
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 102567c35e1c4d44b9f5734fc78c522b
+17
View File
@@ -0,0 +1,17 @@
{
"name": "Rhyculator.Game",
"rootNamespace": "",
"references": [
"Unity.InputSystem",
"UnityEngine.UI"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a1e14a99d24120545ac8d1ec87adf041
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+11
View File
@@ -0,0 +1,11 @@
// 伺服器網址集中管理
// 本地測試:UseLocal = true,並對模擬器執行
// adb reverse tcp:2010 tcp:2010
// adb reverse tcp:2030 tcp:2030
public static class ServerConfig
{
public const bool UseLocal = true;
public const string GameServerUrl = UseLocal ? "http://127.0.0.1:2010" : "https://lunchpad.sthkm3.org";
public const string VerifyServerUrl = UseLocal ? "http://127.0.0.1:2030" : "https://verify.sthkm3.org";
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9d6e31a65e930824991bf2a768205f09
+36
View File
@@ -0,0 +1,36 @@
using UnityEngine;
using UnityEngine.UI;
public class ShowUID : MonoBehaviour
{
public Text displayText;
void Start()
{
int uid = PlayerPrefs.GetInt("UID", 0);
string type = PlayerPrefs.GetString("Type", "");
string uidHex;
if (uid != 0 && !string.IsNullOrEmpty(type))
{
char typeChar = type switch
{
"R" => '0',
"A" => 'a',
"B" => 'b',
"D" => 'f',
_ => '?'
};
string uidHexPart = uid.ToString("X8");
uidHex = $"{typeChar}x{uidHexPart}";
}
else
{
uidHex = "0x00000000";
}
displayText.text = "UID: " + uidHex;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d37d15764a6dd8d419c9acb03ea61106
+58
View File
@@ -0,0 +1,58 @@
using UnityEngine;
// 以音訊 DSP 時鐘為準的歌曲時間(秒)
// AudioSettings.dspTime 在手機上是以音訊 buffer 為單位跳動,
// 這裡用 realtime 在兩次跳動之間補間,並保證時間單調遞增
public static class SongClock
{
public static bool Running { get; private set; }
private static double dspStart;
private static double lastDsp;
private static double lastDspRealtime;
private static double lastReturned;
private static double offsetSec;
// 補間最多往前推 0.1 秒,避免音訊卡住時畫面跑太快
private const double MaxExtrapolation = 0.1;
public const string OffsetPrefKey = "AudioOffsetMs";
// applyOffset = false:不套用延遲補償(校正量測時使用)
public static void Begin(double dspStartTime, bool applyOffset = true)
{
dspStart = dspStartTime;
lastDsp = AudioSettings.dspTime;
lastDspRealtime = Time.realtimeSinceStartupAsDouble;
lastReturned = double.MinValue;
offsetSec = applyOffset ? PlayerPrefs.GetInt(OffsetPrefKey, 0) / 1000.0 : 0;
Running = true;
}
public static void Stop()
{
Running = false;
}
// 目前歌曲時間;音樂開始前為負值
public static double Now
{
get
{
if (!Running) return 0;
double dsp = AudioSettings.dspTime;
double real = Time.realtimeSinceStartupAsDouble;
if (dsp != lastDsp)
{
lastDsp = dsp;
lastDspRealtime = real;
}
double t = lastDsp + System.Math.Min(real - lastDspRealtime, MaxExtrapolation) - dspStart - offsetSec;
if (t < lastReturned) t = lastReturned;
lastReturned = t;
return t;
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 352b164fefd8c6b45bb274076fffc604
+87
View File
@@ -0,0 +1,87 @@
using System;
using System.IO;
using System.Text.RegularExpressions;
// 一個已匯入曲包的資訊(來自 config.json 與資料夾內的檔案)
// 曲包格式見 RhyculatorMaker 的 README
public class SongInfo
{
public const int LevelCount = 3;
public static readonly string[] LevelNames = { "easy", "normal", "hard" }; // level 1..3
public static readonly string[] MusicNames = { "music.ogg", "music.wav", "music.mp3" };
public const string ConfigName = "config.json";
public const string ImageName = "image.png";
public const string VideoName = "video.mp4";
private static readonly Regex IdPattern = new Regex("^[a-z0-9][a-z0-9-]{1,63}$");
public string id;
public string name;
public string artist;
public string charter;
public double bpm;
public int beatOffsetMs;
public int offsetMs; // 判定時間微調:正值 = 所有音符的判定點往後移
public int previewStartMs;
public int previewLengthMs;
public readonly int[] levelNum = new int[LevelCount + 1]; // [1..3] 難度數字,0 = 未填
public string dir;
public static string LevelName(int level) => level >= 1 && level <= LevelCount ? LevelNames[level - 1] : "normal";
public static bool IsValidId(string id) => id != null && IdPattern.IsMatch(id);
public bool HasLevel(int level) => level >= 1 && level <= LevelCount && File.Exists(ChartPath(level));
public string ChartPath(int level) => Path.Combine(dir, LevelName(level) + ".json");
public string ImagePath => Path.Combine(dir, ImageName);
public string VideoPath
{
get { string p = Path.Combine(dir, VideoName); return File.Exists(p) ? p : null; }
}
public string MusicPath
{
get
{
foreach (var n in MusicNames)
{
string p = Path.Combine(dir, n);
if (File.Exists(p)) return p;
}
return null;
}
}
// 第一個有譜面的難度,沒有則 0
public int FirstLevel()
{
for (int l = 1; l <= LevelCount; l++) if (HasLevel(l)) return l;
return 0;
}
// 解析 config.json;缺必要欄位時丟 FormatException
public static SongInfo FromConfig(string configJson, string dir)
{
var cfg = MiniJson.AsObject(MiniJson.Parse(configJson));
if (cfg == null) throw new FormatException("config.json 不是 JSON 物件");
var s = new SongInfo { dir = dir };
s.id = MiniJson.GetString(cfg, "id", "").Trim();
if (!IsValidId(s.id)) throw new FormatException("config.json 的 id 無效(只能用小寫英數字與 -)");
s.name = MiniJson.GetString(cfg, "name", "").Trim();
if (s.name == "") throw new FormatException("config.json 缺少 name");
s.artist = MiniJson.GetString(cfg, "artist", "");
s.charter = MiniJson.GetString(cfg, "charter", "");
s.bpm = MiniJson.GetNumber(cfg, "bpm", 0);
s.beatOffsetMs = MiniJson.GetInt(cfg, "beat_offset", 0);
s.offsetMs = MiniJson.GetInt(cfg, "offset", 0);
s.previewStartMs = MiniJson.GetInt(cfg, "preview_start", 0);
s.previewLengthMs = MiniJson.GetInt(cfg, "preview_length", 15000);
for (int l = 1; l <= LevelCount; l++)
s.levelNum[l] = MiniJson.GetInt(cfg, LevelNames[l - 1] + "_num", 0);
return s;
}
public static SongInfo FromDir(string dir)
=> FromConfig(File.ReadAllText(Path.Combine(dir, ConfigName)), dir);
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 662e3c38dfd560f41a15cfe5a56b4cd2
+73
View File
@@ -0,0 +1,73 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
// 已匯入的曲包清單:persistentDataPath/songs/<id>/
// 遊戲本身不內建任何曲目,所有歌曲都由曲包匯入
public static class SongLibrary
{
public const string CurrentPrefKey = "NowPlayingSong";
// Android 端(RhyculatorActivity.java)讀取失敗時寫在收件匣的訊息檔
public const string ImportErrorFile = "import-error.txt";
// 測試用:改放到別的資料夾
public static string rootOverride;
public static string RootDir => rootOverride ?? Path.Combine(Application.persistentDataPath, "songs");
// 放在這個資料夾的 *.zip 會在開啟遊戲 / 回到前景時自動匯入
public static string InboxDir => rootOverride != null ? Path.Combine(rootOverride, "inbox") : Application.persistentDataPath;
private static List<SongInfo> songs;
public static IReadOnlyList<SongInfo> Songs
{
get { if (songs == null) Reload(); return songs; }
}
public static void Reload()
{
var list = new List<SongInfo>();
if (Directory.Exists(RootDir))
{
foreach (var dir in Directory.GetDirectories(RootDir))
{
if (!File.Exists(Path.Combine(dir, SongInfo.ConfigName))) continue;
try
{
var s = SongInfo.FromDir(dir);
if (s.MusicPath != null && s.FirstLevel() > 0) list.Add(s);
else Debug.LogWarning($"[SongLibrary] 略過 {dir}:缺音樂或譜面");
}
catch (System.Exception e)
{
Debug.LogWarning($"[SongLibrary] 略過 {dir}:{e.Message}");
}
}
}
list.Sort((a, b) => string.Compare(a.name, b.name, System.StringComparison.OrdinalIgnoreCase));
songs = list;
}
public static SongInfo Find(string id)
{
foreach (var s in Songs) if (s.id == id) return s;
return null;
}
// 目前選擇的曲目;沒選過或已被刪除時取清單第一首
public static SongInfo Current
{
get
{
var s = Find(PlayerPrefs.GetString(CurrentPrefKey, ""));
return s ?? (Songs.Count > 0 ? Songs[0] : null);
}
set
{
if (value == null) return;
PlayerPrefs.SetString(CurrentPrefKey, value.id);
PlayerPrefs.Save();
}
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7ff7d094ad9b04649a25edb101c020e3
+84
View File
@@ -0,0 +1,84 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 畫面下方的短訊息(跨場景保留),例如「已匯入曲包」
public class Toast : MonoBehaviour
{
private static Toast instance;
private readonly Queue<string> queue = new Queue<string>();
private Text text;
private CanvasGroup group;
private Coroutine running;
public static void Show(string message)
{
Debug.Log("[Toast] " + message);
if (instance == null) instance = Create();
instance.queue.Enqueue(message);
if (instance.running == null) instance.running = instance.StartCoroutine(instance.Run());
}
private static Toast Create()
{
var root = new GameObject("Toast", typeof(Canvas), typeof(CanvasScaler), typeof(CanvasGroup));
DontDestroyOnLoad(root);
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 500;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 2400);
scaler.matchWidthOrHeight = 0f;
var bg = new GameObject("Background", typeof(RectTransform)).AddComponent<Image>();
bg.transform.SetParent(root.transform, false);
bg.color = new Color(0f, 0f, 0f, 0.82f);
bg.raycastTarget = false;
var rt = bg.rectTransform;
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
rt.anchoredPosition = new Vector2(0, 260);
rt.sizeDelta = new Vector2(960, 150);
var t = new GameObject("Text", typeof(RectTransform)).AddComponent<Text>();
t.transform.SetParent(bg.transform, false);
t.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
t.fontSize = 38;
t.color = Color.white;
t.alignment = TextAnchor.MiddleCenter;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
var trt = t.rectTransform;
trt.anchorMin = Vector2.zero;
trt.anchorMax = Vector2.one;
trt.offsetMin = new Vector2(24, 8);
trt.offsetMax = new Vector2(-24, -8);
var toast = root.AddComponent<Toast>();
toast.text = t;
toast.group = root.GetComponent<CanvasGroup>();
toast.group.alpha = 0f;
return toast;
}
private IEnumerator Run()
{
while (queue.Count > 0)
{
text.text = queue.Dequeue();
group.alpha = 1f;
yield return new WaitForSecondsRealtime(3f);
for (float a = 1f; a > 0f; a -= Time.unscaledDeltaTime * 2f)
{
group.alpha = a;
yield return null;
}
group.alpha = 0f;
}
running = null;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0426c50443e552e4fba1e79de13e96ea
+28
View File
@@ -0,0 +1,28 @@
using UnityEngine;
public class TouchManager_Choose : MonoBehaviour
{
public GridSpawner gridSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public System.Action<int, int> OnTap;
private GridTouchInput input;
void Start()
{
input = new GridTouchInput(gridSpawner, gridSpawner, gridDisplaySpawner);
input.IgnoreCurrentTouches();
}
void Update()
{
foreach (var t in input.Poll())
{
if (!t.OnCell) continue;
if (t.began) OnTap?.Invoke(t.x, t.y);
gridSpawner.gridCells[t.x, t.y].FlashWhite();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8edd82bbcbc736044b9ad71729b8d755
+88
View File
@@ -0,0 +1,88 @@
using UnityEngine;
using UnityEngine.UI;
public class TouchManager_Main : MonoBehaviour
{
public GridSpawner gridSpawner;
public HoldHintSpawner holdHintSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public Text scoreLabel;
public System.Action<int, int> OnTap;
public System.Action<int, int> OnHoldStart;
public System.Action OnHoldEnd;
private GridTouchInput input;
private int holdFingerId = -1;
void Start()
{
input = new GridTouchInput(gridSpawner, gridSpawner, gridDisplaySpawner, holdHintSpawner);
input.IgnoreCurrentTouches();
}
void Update()
{
foreach (var t in input.Poll())
{
if (t.ended)
{
if (t.fingerId == holdFingerId)
{
holdFingerId = -1;
OnHoldEnd?.Invoke();
}
continue;
}
if (!t.OnCell) continue;
var cell = gridSpawner.gridCells[t.x, t.y];
if (!t.began)
{
cell.FlashWhite();
continue;
}
OnTap?.Invoke(t.x, t.y);
if (t.x == 2 && t.y == 2 && holdFingerId < 0)
{
holdFingerId = t.fingerId;
OnHoldStart?.Invoke(t.x, t.y);
cell.FlashBlue();
}
else
{
CheckNoteTimingAndFlash(t.x, t.y, SongClock.Now - t.pressAge);
}
}
}
// 主畫面背景音符:點擊時顯示 Early / Late 毫秒數(可當作延遲校正參考)
void CheckNoteTimingAndFlash(int x, int y, double pressTime)
{
if (gridDisplaySpawner == null || !gridDisplaySpawner.HasNote(x, y)) return;
double delta = pressTime - gridDisplaySpawner.GetHitTime(x, y);
Judgement j = NoteJudge.Evaluate(delta);
if (j == Judgement.None || j == Judgement.Miss) return;
var cell = gridSpawner.gridCells[x, y];
switch (j)
{
case Judgement.Perfect: cell.FlashBlue(); break; // 藍色
case Judgement.Slow: cell.FlashOrange(); break; // 慢 橙色
case Judgement.Fast: cell.FlashGreen(); break; // 快 綠色
case Judgement.Bad: cell.FlashRed(); break; // 紅色
}
gridDisplaySpawner.Clear(x, y);
ShowOffset((int)System.Math.Round(delta * 1000));
}
private void ShowOffset(int ms)
{
if (scoreLabel == null) return;
scoreLabel.text = (ms < 0 ? "Early " : "Late ") + System.Math.Abs(ms) + "ms";
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fc50e9d71050eb1428c8193cb12c8d43
+182
View File
@@ -0,0 +1,182 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TouchManager_Playing : MonoBehaviour
{
public GridSpawner gridSpawner;
public HoldHintSpawner holdHintSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public Text scoreLabel;
private const int HOLD_FULL_SCORE = 212;
private const int SLIDE_SCORE = 106;
public PlayResult Result { get; } = new PlayResult();
private GridTouchInput input;
// 按住中的 Hold(可同時多個)
private class ActiveHold
{
public int x, y, fingerId;
public double hitTime, duration;
public Judgement head;
}
private readonly List<ActiveHold> holds = new List<ActiveHold>();
void Start()
{
input = new GridTouchInput(gridSpawner, gridSpawner, gridDisplaySpawner, holdHintSpawner);
input.IgnoreCurrentTouches();
}
void OnEnable()
{
if (gridDisplaySpawner != null) gridDisplaySpawner.NoteExpired += HandleNoteExpired;
}
void OnDisable()
{
if (gridDisplaySpawner != null) gridDisplaySpawner.NoteExpired -= HandleNoteExpired;
}
void Update()
{
double now = SongClock.Now;
// Hold 按滿時間 → 自動結算
for (int i = holds.Count - 1; i >= 0; i--)
if (now >= holds[i].hitTime + holds[i].duration)
FinishHold(holds[i], now);
foreach (var t in input.Poll())
{
if (t.ended)
{
var h = holds.Find(a => a.fingerId == t.fingerId);
if (h != null) FinishHold(h, now);
continue;
}
if (!t.OnCell) continue;
// 空按也亮白色(不覆蓋判定色)
if (!gridDisplaySpawner.HasNote(t.x, t.y))
{
gridSpawner.gridCells[t.x, t.y].FlashWhite();
continue;
}
// 按下的精確時間(觸控事件時間回推),不受幀率影響
double pressTime = now - t.pressAge;
string noteType = gridDisplaySpawner.GetCurrentNote(t.x, t.y);
if (noteType == "Tap")
{
if (t.began) ProcessTap(t.x, t.y, pressTime);
}
else if (noteType == "Hold")
{
if (t.began)
{
int holdMs = gridDisplaySpawner.GetCurrentSec(t.x, t.y);
double hit = gridDisplaySpawner.GetHitTime(t.x, t.y);
Judgement j = JudgeHead(t.x, t.y, pressTime);
if (j != Judgement.None && holdMs > 0)
{
// Hold 頭判先記住,按滿才給分
FlashJudgement(t.x, t.y, j);
gridDisplaySpawner.Clear(t.x, t.y);
var h = new ActiveHold
{
x = t.x, y = t.y, fingerId = t.fingerId,
hitTime = hit, duration = holdMs / 1000.0, head = j
};
holds.Add(h);
holdHintSpawner.StartProgressAt(t.x, t.y, (float)(hit + h.duration - now));
}
}
}
else if (noteType == "Slide")
{
// Slide 不提早判定:到達判定點後手指在格子上即算接到(可延遲到判定窗結束)
if (now >= gridDisplaySpawner.GetHitTime(t.x, t.y))
{
gridSpawner.gridCells[t.x, t.y].FlashBlue();
gridDisplaySpawner.Clear(t.x, t.y);
AddScore(Judgement.Perfect, SLIDE_SCORE);
}
}
}
}
void FinishHold(ActiveHold h, double now)
{
bool completed = now >= h.hitTime + h.duration - 0.02;
var cell = gridSpawner.gridCells[h.x, h.y];
if (completed)
{
// 按滿:頭判分數 + 持續段分數
cell.FlashBlue();
AddScore(h.head, NoteJudge.Score(h.head) + HOLD_FULL_SCORE);
}
else
{
// 提早放開:亮紅色、不給分
cell.FlashRed();
AddScore(Judgement.Miss, 0);
}
holdHintSpawner.StopProgressAt(h.x, h.y);
holds.Remove(h);
}
void HandleNoteExpired(int x, int y, string note)
{
gridSpawner.gridCells[x, y].FlashRed();
AddScore(Judgement.Miss, 0);
}
// 只做判定,不給分、不清除(None = 不在判定範圍)
Judgement JudgeHead(int x, int y, double pressTime)
{
Judgement j = NoteJudge.Evaluate(pressTime - gridDisplaySpawner.GetHitTime(x, y));
return j == Judgement.Miss ? Judgement.None : j;
}
void FlashJudgement(int x, int y, Judgement j)
{
var cell = gridSpawner.gridCells[x, y];
switch (j)
{
case Judgement.Perfect: cell.FlashBlue(); break;
case Judgement.Fast: cell.FlashGreen(); break;
case Judgement.Slow: cell.FlashOrange(); break;
case Judgement.Bad: cell.FlashRed(); break;
}
}
// Tap:判定、給分、清除;回傳是否有判定到音符
bool ProcessTap(int x, int y, double pressTime)
{
Judgement j = JudgeHead(x, y, pressTime);
if (j == Judgement.None) return false;
FlashJudgement(x, y, j);
AddScore(j, NoteJudge.Score(j));
gridDisplaySpawner.Clear(x, y);
return true;
}
private void AddScore(Judgement j, int amount)
{
Result.Add(j, amount);
ShowScore();
}
private void ShowScore()
{
if (scoreLabel != null)
scoreLabel.text = Result.score.ToString();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ccc33514d4a4f85478cb9bd84b5e295b
+52
View File
@@ -0,0 +1,52 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 找出螢幕某點最上層的 UI 圖形(不依賴 EventSystem,主畫面沒有 EventSystem)
public static class UIHitTest
{
// 該點最上層是否為「格子以外」的 UI(面板、按鈕、圖片…),是的話格子不該接收這次觸控
// 文字不視為阻擋物(例如 UID、版本號、分數)
public static bool IsBlocked(Vector2 screenPos, IList<Transform> gridRoots)
{
Graphic top = TopmostGraphicAt(screenPos);
if (top == null) return false;
foreach (var root in gridRoots)
if (root != null && top.transform.IsChildOf(root)) return false;
return true;
}
public static Graphic TopmostGraphicAt(Vector2 screenPos)
{
Graphic top = null;
long topKey = long.MinValue;
foreach (var canvas in Object.FindObjectsByType<Canvas>(FindObjectsSortMode.None))
{
if (!canvas.isActiveAndEnabled) continue;
Canvas root = canvas.rootCanvas;
bool overlay = root.renderMode == RenderMode.ScreenSpaceOverlay;
Camera cam = overlay ? null : root.worldCamera;
var graphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(canvas);
for (int i = 0; i < graphics.Count; i++)
{
Graphic g = graphics[i];
if (g is Text) continue;
if (!g.isActiveAndEnabled || g.depth < 0 || g.canvasRenderer.cull) continue;
if (!RectTransformUtility.RectangleContainsScreenPoint(g.rectTransform, screenPos, cam)) continue;
// 排序:Overlay 畫布在最上層 → 畫布 sortingOrder → 畫布內繪製順序
long key = ((overlay ? 1L : 0L) << 48) + ((long)(canvas.sortingOrder + 32768) << 24) + g.depth;
if (key > topKey)
{
topKey = key;
top = g;
}
}
}
return top;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b514edd2240c764db075f214a207d42
+409
View File
@@ -0,0 +1,409 @@
using UnityEngine;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using UnityEngine.Networking;
using System.Collections;
public class AccountUIManager : MonoBehaviour
{
[Header("Panels")]
public GameObject LoginPanel;
public GameObject RegisterPanel;
public GameObject VerifyPanel;
public GameObject AccountPanel;
[Header("Login")]
public InputField LoginIDInput;
public InputField LoginPasswordInput;
[Header("Register")]
public InputField EmailInput;
public InputField IDInput;
public InputField PasswordInput;
public InputField PasswordVerifyInput;
public Text ErrorLabel;
[Header("Verify")]
public InputField VerifyInput;
private const string GameServerUrl = ServerConfig.GameServerUrl;
private const string VerifyServerUrl = ServerConfig.VerifyServerUrl;
[System.Serializable]
public class VerifyRequest
{
public string game;
public string email;
public string code;
public string password;
}
public class Request
{
public string request;
public string uid;
public string email;
public string name;
public string password;
public string token;
}
public class Response
{
public string status;
public string reason;
public string token;
public int uid;
public string name;
public string create_time;
public string account_type;
public string email = "";
public int email_v;
public string phone = "";
public int phone_v;
}
void Start()
{
int uid = PlayerPrefs.GetInt("UID", 0);
// 新版存 Token;舊版存 Password(進帳號頁時會自動換成 Token)
bool hasCredential = PlayerPrefs.HasKey("Token") || PlayerPrefs.HasKey("Password");
if (uid == 0 || !hasCredential)
{
ShowLoginPanel();
}
else
ShowAccountPanel();
}
public void ShowAccountPanel()
{
StartCoroutine(AccountFlow());
AccountPanel.SetActive(true);
LoginPanel.SetActive(false);
RegisterPanel.SetActive(false);
VerifyPanel.SetActive(false);
}
public void ShowLoginPanel()
{
AccountPanel.SetActive(false);
LoginPanel.SetActive(true);
RegisterPanel.SetActive(false);
VerifyPanel.SetActive(false);
}
public void ShowRegisterPanel()
{
AccountPanel.SetActive(false);
LoginPanel.SetActive(false);
RegisterPanel.SetActive(true);
VerifyPanel.SetActive(false);
}
public void ShowVerifyPanel()
{
AccountPanel.SetActive(false);
LoginPanel.SetActive(false);
RegisterPanel.SetActive(false);
VerifyPanel.SetActive(true);
}
public void LogOut()
{
string token = PlayerPrefs.GetString("Token", "");
if (!string.IsNullOrEmpty(token))
StartCoroutine(PostJson(GameServerUrl, JsonUtility.ToJson(new Request { request = "logout", token = token }), _ => { }));
PlayerPrefs.DeleteKey("Token");
PlayerPrefs.DeleteKey("UID");
PlayerPrefs.DeleteKey("Password");
PlayerPrefs.Save();
ShowLoginPanel();
}
private void ClearError()
{
if (ErrorLabel != null)
ErrorLabel.text = "";
}
private void ShowError(string message)
{
if (ErrorLabel != null)
ErrorLabel.text = message;
Debug.LogError(message);
}
public void SendRegisterData()
{
StartCoroutine(RegisterFlow());
}
public void SendVerifyData()
{
ClearError();
StartCoroutine(SendVerifyRequest(PlayerPrefs.GetString("Email", ""), VerifyInput.text.Trim(), Credential()));
}
public void SendLoginData()
{
StartCoroutine(LoginFlow());
}
// 驗證用憑證:Token 優先,舊版才用密碼
private static string Credential()
{
string token = PlayerPrefs.GetString("Token", "");
return string.IsNullOrEmpty(token) ? PlayerPrefs.GetString("Password", "") : token;
}
private IEnumerator SendVerifyRequest(string email, string code = "", string password = "")
{
string jsonData = JsonUtility.ToJson(new VerifyRequest
{
game = "lunchpad",
email = email,
code = code,
password = password
});
Response response = null;
yield return PostJson(VerifyServerUrl, jsonData, r => response = r);
if (response == null) yield break;
if (response.status == "send")
{
ShowVerifyPanel();
}
else if (response.status == "success")
{
ShowAccountPanel();
}
else if (response.status == "failed" || response.status == "fail")
{
if (response.reason == "too_many_requests")
ShowError("驗證次數過多,請稍後再試");
else if (response.reason == "game_not_supported")
ShowError("驗證伺服器錯誤,請稍後再試");
else if (response.reason == "wrong_code")
ShowError("驗證碼錯誤");
else if (response.reason == "expired")
ShowError("驗證碼已過期,請重新發送");
else
ShowError("未知錯誤: " + response.reason);
}
else
{
ShowError("驗證伺服器回傳異常");
}
}
// 送出 JSON POST,失敗時顯示錯誤並回傳 null
private IEnumerator PostJson(string url, string json, System.Action<Response> onDone)
{
using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
{
www.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(json));
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
www.timeout = 10;
yield return www.SendWebRequest();
// 伺服器回 4xx/5xx 時 body 仍是 JSON,嘗試解析
Response res = null;
try { res = JsonUtility.FromJson<Response>(www.downloadHandler.text); }
catch { res = null; }
if (res == null || string.IsNullOrEmpty(res.status))
{
ShowError(www.result == UnityWebRequest.Result.ConnectionError
? "無法連線到伺服器" : "伺服器回傳異常");
onDone(null);
yield break;
}
onDone(res);
}
}
private IEnumerator RegisterFlow()
{
string email = EmailInput.text.Trim();
string id = IDInput.text.Trim();
string password = PasswordInput.text;
string passwordVerify = PasswordVerifyInput.text;
ClearError();
if (email.Length < 10 || !Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
{
ShowError("請輸入有效的電子郵件地址");
yield break;
}
if(id.Length < 4)
{
ShowError("ID 長度不足 4 位");
yield break;
}
if (password.Length < 6)
{
ShowError("密碼長度不足 6 位");
yield break;
}
if (!Regex.IsMatch(password, @"^(?=.*[a-zA-Z])(?=.*\d).+$"))
{
ShowError("密碼需包含英文與數字");
yield break;
}
if (password != passwordVerify)
{
ShowError("兩次輸入密碼不一致");
yield break;
}
// 檢查 email 是否存在
var findEmailObj = new Request {
request = "find_email",
email = email
};
Response res1 = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(findEmailObj), r => res1 = r);
if (res1 == null) yield break;
if (res1.status == "found")
{
ShowError("信箱已被註冊!");
yield break;
}
// 檢查 name 是否存在
var findNameObj = new Request {
request = "find_name",
name = id
};
Response res2 = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(findNameObj), r => res2 = r);
if (res2 == null) yield break;
if (res2.status == "found")
{
ShowError("ID 已被使用!");
yield break;
}
// 開始 create_user
var createUserObj = new Request {
request = "create_user",
email = email,
name = id,
password = password
};
Response res3 = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(createUserObj), r => res3 = r);
if (res3 == null) yield break;
if (res3.status != "success")
{
ShowError("創建帳號失敗: " + res3.reason);
yield break;
}
// 儲存 email / token → 進入驗證流程(不再儲存密碼)
PlayerPrefs.SetInt("UID", res3.uid);
PlayerPrefs.SetString("Email", email);
PlayerPrefs.SetString("Token", res3.token);
PlayerPrefs.DeleteKey("Password");
PlayerPrefs.Save();
StartCoroutine(SendVerifyRequest(email));
}
private IEnumerator LoginFlow()
{
string id = LoginIDInput.text.Trim();
string password = LoginPasswordInput.text;
ClearError();
var loginObj = new Request
{
request = "login",
name = id,
password = password
};
Response res = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(loginObj), r => res = r);
if (res == null) yield break;
if (res.status != "success")
{
ShowError("登入失敗: " + res.reason);
yield break;
}
// 儲存
PlayerPrefs.SetInt("UID", res.uid);
PlayerPrefs.SetString("Email", res.email);
PlayerPrefs.SetString("Token", res.token);
PlayerPrefs.DeleteKey("Password");
PlayerPrefs.Save();
ShowAccountPanel();
}
private IEnumerator AccountFlow()
{
string uid = PlayerPrefs.GetInt("UID", 0).ToString();
string token = PlayerPrefs.GetString("Token", "");
string password = PlayerPrefs.GetString("Password", "");
ClearError();
var personObj = new Request
{
request = "person_info",
uid = uid,
token = token,
password = string.IsNullOrEmpty(token) ? password : null
};
Response res = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(personObj), r => res = r);
if (res == null) yield break;
if (res.status != "success")
{
ShowError("載入失敗: " + res.reason);
yield break;
}
PlayerPrefs.SetString("Name", res.name);
PlayerPrefs.SetString("CreateTime", res.create_time);
PlayerPrefs.SetString("Type", res.account_type);
PlayerPrefs.SetString("Email", res.email);
PlayerPrefs.SetInt("EmailVerified", res.email_v);
PlayerPrefs.SetString("Phone", res.phone);
PlayerPrefs.SetInt("PhoneVerified", res.phone_v);
PlayerPrefs.Save();
// 舊版只存了密碼:重新登入換取 Token,並刪除手機上的密碼
if (string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(password))
{
Response login = null;
yield return PostJson(GameServerUrl, JsonUtility.ToJson(new Request { request = "login", name = res.name, password = password }), r => login = r);
if (login != null && login.status == "success" && !string.IsNullOrEmpty(login.token))
{
PlayerPrefs.SetString("Token", login.token);
PlayerPrefs.DeleteKey("Password");
PlayerPrefs.Save();
}
}
var display = FindAnyObjectByType<AccountDisplay>();
if (display != null) display.ShowAccountInfo();
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2095ee3cdc687d1469892a47e49f4777
+388
View File
@@ -0,0 +1,388 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
// 選歌:左右切換已匯入的曲包、選難度、看個人最高分 / 排行榜、開始
// 格子配置:(0,5) 分數 (1..3,5) 難度 (4,5) 排行 | (2,3) 目前難度 | (1,2) 上一首 (2,2) 開始 (3,2) 下一首
public class UIManager_Choose : MonoBehaviour
{
public GameObject ScorePanel;
public GameObject RankPanel;
public Text ScoreText;
public Text RankText;
public GridSpawner gridSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public string PlayingSceneName = "PlayingScene";
public TouchManager_Choose touchManager;
public Sprite imgStart;
public Sprite imgArrowRight;
public Sprite imgArrrowLeft;
public Sprite imgScore;
public Sprite imgRank;
[Header("曲目顯示")]
public Image coverImage;
public Text nameLabel;
public AudioSource previewSource;
private static readonly Color[] LevelColors =
{
Color.white,
new Color(0.49f, 0.84f, 0.49f), // easy
new Color(1f, 0.31f, 0.31f), // normal
new Color(0.71f, 0.39f, 1f), // hard
};
private IReadOnlyList<SongInfo> songs;
private int index;
private int level;
private readonly Dictionary<string, Sprite> covers = new Dictionary<string, Sprite>();
private int previewGeneration;
private AudioClip previewClip;
private float previewStart, previewEnd;
private Text emptyHint;
private SongInfo Song => songs.Count > 0 ? songs[index] : null;
void Start()
{
touchManager.OnTap += HandleTap;
songs = SongLibrary.Songs;
var current = SongLibrary.Current;
index = 0;
for (int i = 0; i < songs.Count; i++)
if (songs[i] == current) index = i;
level = PlayerPrefs.GetInt("NowPlayingLevel", 1);
ShowSong();
}
void OnDestroy()
{
previewGeneration++;
if (previewSource != null) previewSource.Stop();
if (previewClip != null) Destroy(previewClip);
foreach (var s in covers.Values)
{
if (s == null) continue;
Destroy(s.texture);
Destroy(s);
}
}
void Update()
{
// 試聽片段循環
if (previewSource != null && previewSource.isPlaying && previewEnd > previewStart && previewSource.time >= previewEnd)
previewSource.time = previewStart;
}
// 面板開著時,格子不接受操作(避免穿透誤觸)
bool IsPanelOpen => ScorePanel.activeSelf || RankPanel.activeSelf;
void ShowSong()
{
var song = Song;
bool many = songs.Count > 1;
gridDisplaySpawner.SetImage(1, 2, many ? imgArrrowLeft : null);
gridDisplaySpawner.SetImage(3, 2, many ? imgArrowRight : null);
if (song == null)
{
ShowEmpty();
return;
}
SongLibrary.Current = song;
if (!song.HasLevel(level)) level = song.FirstLevel();
PlayerPrefs.SetInt("NowPlayingLevel", level);
if (emptyHint != null) emptyHint.gameObject.SetActive(false);
nameLabel.text = string.IsNullOrEmpty(song.artist) ? song.name : $"{song.name} / {song.artist}";
coverImage.sprite = LoadCover(song);
coverImage.preserveAspect = true;
coverImage.enabled = coverImage.sprite != null;
gridDisplaySpawner.SetImage(0, 5, imgScore);
gridDisplaySpawner.SetImage(4, 5, imgRank);
gridDisplaySpawner.SetImage(2, 2, imgStart);
for (int l = 1; l <= SongInfo.LevelCount; l++)
gridDisplaySpawner.SetLabel(l, 5, song.HasLevel(l) ? LevelText(song, l) : null, LevelColors[l]);
gridDisplaySpawner.SetLabel(2, 3, LevelText(song, level), LevelColors[level]);
StartCoroutine(PlayPreview(song));
}
static string LevelText(SongInfo song, int l) => song.levelNum[l] > 0 ? song.levelNum[l].ToString() : "?";
// 沒有任何曲包:顯示匯入方式
void ShowEmpty()
{
nameLabel.text = "";
coverImage.enabled = false;
for (int x = 0; x < 5; x++)
for (int y = 0; y < 6; y++)
gridDisplaySpawner.Clear(x, y);
if (emptyHint == null) emptyHint = CreateHint();
emptyHint.gameObject.SetActive(true);
emptyHint.text = "尚未匯入任何曲包\n\n用檔案管理員或瀏覽器開啟曲包 .zip,\n選擇以「Rhyculator」開啟即可匯入\n\n或把 .zip 放到:\n" + Application.persistentDataPath;
}
Text CreateHint()
{
var go = new GameObject("EmptyHint", typeof(RectTransform));
go.transform.SetParent(coverImage.transform.parent, false);
var t = go.AddComponent<Text>();
t.font = nameLabel.font;
t.fontSize = 40;
t.color = new Color(0.8f, 0.8f, 0.8f);
t.alignment = TextAnchor.MiddleCenter;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
var rt = t.rectTransform;
var cover = coverImage.rectTransform;
rt.anchorMin = cover.anchorMin;
rt.anchorMax = cover.anchorMax;
rt.pivot = cover.pivot;
rt.anchoredPosition = cover.anchoredPosition;
rt.sizeDelta = new Vector2(960, cover.sizeDelta.y);
return t;
}
Sprite LoadCover(SongInfo song)
{
if (covers.TryGetValue(song.id, out var cached)) return cached;
Sprite sprite = null;
try
{
if (File.Exists(song.ImagePath))
{
var tex = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (tex.LoadImage(File.ReadAllBytes(song.ImagePath)))
sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100f);
else
Destroy(tex);
}
}
catch (System.Exception e)
{
Debug.LogWarning($"[Choose] 封面讀取失敗 {song.id}:{e.Message}");
}
covers[song.id] = sprite;
return sprite;
}
IEnumerator PlayPreview(SongInfo song)
{
int generation = ++previewGeneration;
if (previewSource == null) yield break;
previewSource.Stop();
string path = song.MusicPath;
if (path == null) yield break;
AudioClip clip;
using (var www = MusicPlayer.LoadAudio(path))
{
yield return www.SendWebRequest();
if (generation != previewGeneration) yield break; // 已經切到別首
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("[Choose] 試聽載入失敗:" + www.error);
yield break;
}
clip = DownloadHandlerAudioClip.GetContent(www);
}
if (clip == null) yield break;
if (previewClip != null) Destroy(previewClip);
previewClip = clip;
previewStart = Mathf.Clamp(song.previewStartMs / 1000f, 0f, Mathf.Max(0f, clip.length - 1f));
previewEnd = song.previewLengthMs > 0 ? Mathf.Min(clip.length, previewStart + song.previewLengthMs / 1000f) : clip.length;
previewSource.clip = clip;
previewSource.loop = true;
previewSource.time = previewStart;
previewSource.Play();
}
void HandleTap(int x, int y)
{
if (IsPanelOpen) return;
var song = Song;
if (song == null) return;
if (y == 2 && x == 1 && songs.Count > 1)
{
index = (index + songs.Count - 1) % songs.Count;
ShowSong();
}
else if (y == 2 && x == 3 && songs.Count > 1)
{
index = (index + 1) % songs.Count;
ShowSong();
}
else if (y == 5 && x >= 1 && x <= SongInfo.LevelCount)
{
if (!song.HasLevel(x)) return;
level = x;
PlayerPrefs.SetInt("NowPlayingLevel", level);
gridDisplaySpawner.SetLabel(2, 3, LevelText(song, level), LevelColors[level]);
}
else if (y == 5 && x == 0)
{
StartCoroutine(RequestScoreAndShowPanel(song));
}
else if (y == 5 && x == 4)
{
StartCoroutine(RequestRankAndShowPanel(song));
}
else if (y == 2 && x == 2)
{
if (previewSource != null) previewSource.Stop();
SceneManager.LoadScene(PlayingSceneName);
}
}
IEnumerator RequestScoreAndShowPanel(SongInfo song)
{
string jsonData = JsonUtility.ToJson(new ScoreRequest
{
request = "score",
uid = PlayerPrefs.GetInt("UID", 0),
song = song.id,
level = level
});
using (UnityWebRequest www = new UnityWebRequest(ServerConfig.GameServerUrl, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error requesting score: " + www.error);
ScoreText.text = "Error";
}
else
{
ScoreResponse response = JsonUtility.FromJson<ScoreResponse>(www.downloadHandler.text);
ScoreText.text = response.status == "success" ? response.score.ToString() : "0";
}
}
ScorePanel.SetActive(true);
}
IEnumerator RequestRankAndShowPanel(SongInfo song)
{
string jsonData = JsonUtility.ToJson(new RankRequest
{
request = "rank",
song = song.id,
level = level
});
using (UnityWebRequest www = new UnityWebRequest(ServerConfig.GameServerUrl, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error requesting rank: " + www.error);
RankText.text = "Error";
}
else
{
RankResponse response = JsonUtility.FromJson<RankResponse>(www.downloadHandler.text);
if (response.status == "success")
{
string[] names = { response.name_1, response.name_2, response.name_3, response.name_4, response.name_5 };
int[] scores = { response.score_1, response.score_2, response.score_3, response.score_4, response.score_5 };
// 伺服器以 null 表示該名次無人,只顯示有名字的名次
string rankStr = "";
for (int i = 0; i < 5; i++)
{
if (string.IsNullOrEmpty(names[i])) break;
rankStr += $"{i + 1}. {names[i]} - {scores[i]}\n";
}
if (rankStr == "") rankStr = "尚無紀錄";
RankText.text = rankStr;
}
else
{
RankText.text = "No data";
}
}
}
RankPanel.SetActive(true);
}
[System.Serializable]
public class ScoreRequest
{
public string request;
public int uid;
public string song;
public int level;
}
[System.Serializable]
public class ScoreResponse
{
public int score;
public string status;
}
[System.Serializable]
public class RankRequest
{
public string request;
public string song;
public int level;
}
[System.Serializable]
public class RankResponse
{
public string name_1;
public string name_2;
public string name_3;
public string name_4;
public string name_5;
public int score_1;
public int score_2;
public int score_3;
public int score_4;
public int score_5;
public string status;
}
public void QuitScorePanel()
{
ScorePanel.SetActive(false);
}
public void QuitRankPanel()
{
RankPanel.SetActive(false);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9ff06c2deef0cee4ca0c62902b0d3ced
+150
View File
@@ -0,0 +1,150 @@
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using System.Collections; // 必須引入 Coroutine
public class UIManager_Main : MonoBehaviour
{
public GridSpawner gridSpawner;
public HoldHintSpawner holdHintSpawner;
public GridDisplaySpawner gridDisplaySpawner;
public TouchManager_Main touchManager;
public Sprite imgAccount;
public Sprite imgSetting;
public Sprite imgWebsite;
public Sprite imgHoldStart;
public Sprite imgArrowRight;
public Sprite imgArrrowLeft;
public Sprite imgArrrowUp;
public Sprite imgArrrowDown;
public GameObject Start_1;
public GameObject Start_2;
public GameObject Start_3;
public string settingSceneName = "SettingScene";
public string accountSceneName = "AccountScene";
public string chooseSceneName = "ChooseScene";
// 開場動畫只在 app 啟動時播一次
private static bool introShown = false;
// 選單圖示出現前不接受操作(避免點到開場畫面下的格子)
private bool menuReady = false;
private bool isHolding = false;
private bool holdTriggered = false;
private float holdTimer = 0f;
private float holdTarget = 1f;
private int holdX, holdY;
void Start()
{
PlayerPrefs.SetInt("NowPlayingLevel", 1);
Start_1.SetActive(false);
Start_2.SetActive(false);
Start_3.SetActive(false);
if (introShown)
ShowMenu();
else
StartCoroutine(ShowStartPanelsSequence());
touchManager.OnTap += HandleTap;
touchManager.OnHoldStart += StartHold;
touchManager.OnHoldEnd += StopHold;
}
IEnumerator ShowStartPanelsSequence()
{
Start_1.SetActive(true);
yield return new WaitForSeconds(1.885f);
Start_1.SetActive(false);
Start_2.SetActive(true);
yield return new WaitForSeconds(1.846f);
Start_2.SetActive(false);
Start_3.SetActive(true);
yield return new WaitForSeconds(1.846f);
Start_3.SetActive(false);
introShown = true;
ShowMenu();
}
void ShowMenu()
{
menuReady = true;
gridDisplaySpawner.SetImage(1, 5, imgAccount);
gridDisplaySpawner.SetImage(2, 5, imgSetting);
gridDisplaySpawner.SetImage(3, 5, imgWebsite);
gridDisplaySpawner.SetImage(2, 2, imgHoldStart);
gridDisplaySpawner.SetImage(1, 2, imgArrowRight);
gridDisplaySpawner.SetImage(3, 2, imgArrrowLeft);
gridDisplaySpawner.SetImage(2, 1, imgArrrowUp);
gridDisplaySpawner.SetImage(2, 3, imgArrrowDown);
}
void Update()
{
if (isHolding)
{
holdTimer += Time.deltaTime;
if (!holdTriggered && holdTimer >= holdTarget)
{
holdTriggered = true;
// 清圖示
gridDisplaySpawner.Clear(1, 5);
gridDisplaySpawner.Clear(2, 5);
gridDisplaySpawner.Clear(3, 5);
gridDisplaySpawner.Clear(2, 2);
gridDisplaySpawner.Clear(1, 2);
gridDisplaySpawner.Clear(3, 2);
gridDisplaySpawner.Clear(2, 1);
gridDisplaySpawner.Clear(2, 3);
SceneManager.LoadScene(chooseSceneName);
}
}
}
void HandleTap(int x, int y)
{
if (!menuReady) return;
if (x == 1 && y == 5) SceneManager.LoadScene(accountSceneName);
if (x == 2 && y == 5) SceneManager.LoadScene(settingSceneName);
if (x == 3 && y == 5) Application.OpenURL("https://sthkm3.org");
}
void StartHold(int x, int y)
{
if (!menuReady) return;
isHolding = true;
holdTriggered = false;
holdTimer = 0f;
holdX = x;
holdY = y;
holdHintSpawner.StartProgressAt(x, y, holdTarget);
}
void StopHold()
{
if (!isHolding) return;
isHolding = false;
holdTriggered = false;
holdTimer = 0f;
holdHintSpawner.StopProgressAt(holdX, holdY);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 04825755a7bcb6243909e4a5e77d4a2f
+160
View File
@@ -0,0 +1,160 @@
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Networking;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.InputSystem;
public class UIManager_Playing : MonoBehaviour
{
public AudioSource audioSource;
public Text scoreLabel;
private bool finished = false;
private bool started = false;
private MusicPlayer musicPlayer;
private TouchManager_Playing touchManager;
void Start()
{
musicPlayer = FindAnyObjectByType<MusicPlayer>();
touchManager = FindAnyObjectByType<TouchManager_Playing>();
if (scoreLabel != null) scoreLabel.text = "載入中…";
}
void Update()
{
if (musicPlayer == null || finished) return;
// 曲包讀取失敗:回選歌畫面
if (musicPlayer.Error != null)
{
finished = true;
Toast.Show(musicPlayer.Error);
GoToChooseScene();
return;
}
if (!musicPlayer.Ready) return;
if (!started)
{
started = true;
if (scoreLabel != null) scoreLabel.text = "0";
}
// 只觸發一次,避免每幀重複上傳成績
if (musicPlayer.Finished)
{
finished = true;
StartCoroutine(SendScoreAndGoToChooseScene());
}
}
IEnumerator SendScoreAndGoToChooseScene()
{
int uid = PlayerPrefs.GetInt("UID", 0);
SongInfo song = musicPlayer.Song;
int level = musicPlayer.Level;
PlayResult result = touchManager != null ? touchManager.Result : new PlayResult();
PlayResult.Last = result;
Debug.Log($"[Play] song={song.id} level={level} notes={musicPlayer.TotalNotes} {result}");
string status;
if (uid == 0)
{
status = "未登入,成績不會上傳";
}
else
{
bool ok = false;
yield return UploadScore(uid, song, level, result.score, success => ok = success);
status = ok ? "成績已上傳" : "成績上傳失敗";
}
Font font = scoreLabel != null ? scoreLabel.font : null;
if (scoreLabel != null) scoreLabel.gameObject.SetActive(false);
ResultOverlay.Show(result, musicPlayer.TotalNotes, font, status);
yield return WaitForTap();
GoToChooseScene();
}
// 等待一次新的點擊(忽略結算出現前就按著的手指)
IEnumerator WaitForTap()
{
UnityEngine.InputSystem.EnhancedTouch.EnhancedTouchSupport.Enable();
yield return new WaitForSeconds(0.5f);
while (true)
{
foreach (var t in UnityEngine.InputSystem.EnhancedTouch.Touch.activeTouches)
if (t.phase == UnityEngine.InputSystem.TouchPhase.Began) yield break;
if (Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame) yield break;
yield return null;
}
}
IEnumerator UploadScore(int uid, SongInfo song, int level, int score, System.Action<bool> onDone)
{
// 曲包不在伺服器上註冊過時,伺服器會用這些資訊建立歌曲資料
string jsonData = JsonUtility.ToJson(new ScoreData
{
request = "user_play",
uid = uid,
token = PlayerPrefs.GetString("Token", ""),
password = PlayerPrefs.GetString("Password", ""), // 舊版相容
song = song.id,
title = song.name,
artist = song.artist,
bpm = song.bpm,
duration_sec = audioSource != null && audioSource.clip != null ? Mathf.RoundToInt(audioSource.clip.length) : 0,
level = level,
level_num = song.levelNum[level],
score = score
});
using (UnityWebRequest www = new UnityWebRequest(ServerConfig.GameServerUrl, "POST"))
{
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
www.uploadHandler = new UploadHandlerRaw(bodyRaw);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error sending score: " + www.error);
onDone(false);
}
else
{
Debug.Log("Score sent successfully: " + www.downloadHandler.text);
onDone(www.downloadHandler.text.Contains("\"success\""));
}
}
}
void GoToChooseScene()
{
if (SceneManager.GetActiveScene().name != "ChooseScene")
{
SceneManager.LoadScene("ChooseScene");
}
}
[System.Serializable]
public class ScoreData
{
public string request;
public int uid;
public string token;
public string password;
public string song;
public string title;
public string artist;
public double bpm;
public int duration_sec;
public int level;
public int level_num;
public int score;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3e2f63f884d58af43bafffd2c824e590
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d4aec1eb2ed146443b9a41e082f95616
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
using UnityEngine;
using UnityEngine.UI;
public class GridDisplay_MainScene : MonoBehaviour
{
public GridManager_MainScene gridManager;
public Sprite imgAccount;
public Sprite imgSetting;
public Sprite imgWebsite;
private bool initialized = false;
void Update()
{
// 等待 GridManager
if (!initialized && gridManager != null && gridManager.gridCells != null)
{
if (gridManager.gridCells[0,0] != null)
{
InitDisplay();
initialized = true;
}
}
}
void InitDisplay()
{
PlaceImage(1, 5, imgAccount);
PlaceImage(2, 5, imgSetting);
PlaceImage(3, 5, imgWebsite);
}
void PlaceImage(int cellX, int cellY, Sprite sprite)
{
var cell = gridManager.gridCells[cellX, cellY];
if (cell == null) return;
GameObject obj = new GameObject("DisplayIcon", typeof(RectTransform), typeof(Image));
obj.transform.SetParent(cell.transform, false);
Image img = obj.GetComponent<Image>();
img.sprite = sprite;
img.preserveAspect = true;
RectTransform rt = obj.GetComponent<RectTransform>();
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = Vector2.zero;
rt.offsetMax = Vector2.zero;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b8c7d3a3af0b5554089fa9c8ef5b0ac1
+125
View File
@@ -0,0 +1,125 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
public class GridManager : MonoBehaviour
{
public GameObject cellPrefab; // Grid_cell 預製件
public int rows = 6;
public int columns = 5;
public GridColor[,] gridCells;
public string settingSceneName = "SettingScene";
void Start()
{
// === 這裡設定比例 ===
float baseWidth = 1080f; // 你的基準寬度
float cellBase = 180f; // 格子原始比例
float spaceBase = 20f; // 間距原始比例
float heightBase = 90f; // 上推高度 邊60*1.5
// 以螢幕寬度計算等比例縮放
float scale = Screen.width / baseWidth;
float cellSize = cellBase * scale;
float spacing = spaceBase * scale;
float heightOffset = heightBase * scale;
// 建立二維陣列
gridCells = new GridColor[columns, rows];
// 計算最底部開始的起點 (Bottom Center)
RectTransform rt = GetComponent<RectTransform>();
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
// 保證錨點是 bottom center
rt.anchorMin = new Vector2(0.5f, 0f);
rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
// 整個 grid 的寬度
float totalWidth = columns * cellSize + (columns - 1) * spacing;
// 左邊起點(因為錨點是中心)
float startX = -totalWidth / 2f;
// Y 起點永遠是 0(底部)
float startY = heightOffset;
for (int i = 0; i < rows * columns; i++)
{
// 生成格子
GameObject cellObj = Instantiate(cellPrefab, transform);
int x = i % columns;
int y = i / columns;
RectTransform cellRT = cellObj.GetComponent<RectTransform>();
// 設定錨點跟 pivot(全用左下)
cellRT.anchorMin = new Vector2(0f, 0f);
cellRT.anchorMax = new Vector2(0f, 0f);
cellRT.pivot = new Vector2(0f, 0f);
// 設定大小
cellRT.sizeDelta = new Vector2(cellSize, cellSize);
// 計算位置(由下往上排列)
float posX = startX + x * (cellSize + spacing);
float posY = startY + y * (cellSize + spacing);
cellRT.anchoredPosition = new Vector2(posX, posY);
// 設定 GridColor
GridColor cellColor = cellObj.GetComponent<GridColor>();
cellColor.cellX = x;
cellColor.cellY = y;
gridCells[x, y] = cellColor;
}
}
void Update()
{
DetectTouch();
}
void DetectTouch()
{
if (Touchscreen.current == null) return;
foreach (var touch in Touchscreen.current.touches)
{
if (!touch.isInProgress) continue;
Vector2 touchPos = touch.position.ReadValue();
var phase = touch.phase.ReadValue();
// 判定落在哪個格子
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
var cell = gridCells[x, y];
if (RectTransformUtility.RectangleContainsScreenPoint(
cell.GetComponent<RectTransform>(), touchPos))
{
if (phase == UnityEngine.InputSystem.TouchPhase.Began)
{
// 按下瞬間
cell.FlashBlue();
}
else
{
// 持續觸摸
cell.FlashWhite();
}
}
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 16721c86445ac454e93e37ff47b7945b
@@ -0,0 +1,166 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class GridManager_MainScene : MonoBehaviour
{
public GameObject cellPrefab;
public int rows = 6;
public int columns = 5;
public GridColor[,] gridCells;
// Hold 參數
private bool isHolding = false;
private float holdTimer = 0f;
private float holdTarget = 1f;
private bool holdingCell = false;
private bool holdTriggered = false;
private int holdX, holdY;
public HoldHintSpawner holdProgressManager;
public string settingSceneName = "SettingScene";
public string accountSceneName = "AccountScene";
void Start()
{
float baseWidth = 1080f;
float cellBase = 180f;
float spaceBase = 20f;
float heightBase = 90f;
float scale = Screen.width / baseWidth;
float cellSize = cellBase * scale;
float spacing = spaceBase * scale;
float heightOffset = heightBase * scale;
gridCells = new GridColor[columns, rows];
RectTransform rt = GetComponent<RectTransform>();
if (rt == null) rt = gameObject.AddComponent<RectTransform>();
rt.anchorMin = new Vector2(0.5f, 0f);
rt.anchorMax = new Vector2(0.5f, 0f);
rt.pivot = new Vector2(0.5f, 0f);
float totalWidth = columns * cellSize + (columns - 1) * spacing;
float startX = -totalWidth / 2f;
float startY = heightOffset;
for (int i = 0; i < rows * columns; i++)
{
GameObject cellObj = Instantiate(cellPrefab, transform);
int x = i % columns;
int y = i / columns;
RectTransform cellRT = cellObj.GetComponent<RectTransform>();
cellRT.anchorMin = new Vector2(0f, 0f);
cellRT.anchorMax = new Vector2(0f, 0f);
cellRT.pivot = new Vector2(0f, 0f);
cellRT.sizeDelta = new Vector2(cellSize, cellSize);
float posX = startX + x * (cellSize + spacing);
float posY = startY + y * (cellSize + spacing);
cellRT.anchoredPosition = new Vector2(posX, posY);
GridColor cellColor = cellObj.GetComponent<GridColor>();
cellColor.cellX = x;
cellColor.cellY = y;
gridCells[x, y] = cellColor;
}
}
void Update()
{
DetectTouch();
// 按住 → 開始倒數
if (isHolding)
{
holdTimer += Time.deltaTime;
if (!holdTriggered && holdTimer >= holdTarget)
{
holdTriggered = true;
Debug.Log("成功");
}
}
}
void DetectTouch()
{
if (Touchscreen.current == null) return;
foreach (var touch in Touchscreen.current.touches)
{
UnityEngine.InputSystem.TouchPhase phase = touch.phase.ReadValue();
Vector2 touchPos = touch.position.ReadValue();
// ------------------------------------
// 若正在長按,不再判斷是否還在格子內
// ------------------------------------
if (holdingCell)
{
if (phase == UnityEngine.InputSystem.TouchPhase.Ended || phase == UnityEngine.InputSystem.TouchPhase.Canceled)
{
// 放開 → 結束
isHolding = false;
holdingCell = false;
holdTimer = 0f;
holdTriggered = false;
holdProgressManager.StopProgressAt(holdX, holdY);
}
return; // 已經在長按 → 不再找其他格子
}
// -------------------------------------------------------
// 如果沒有在 holding,這裡才會尋找目前手指所在格子
// -------------------------------------------------------
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
var cell = gridCells[x, y];
if (RectTransformUtility.RectangleContainsScreenPoint(
cell.GetComponent<RectTransform>(), touchPos))
{
cell.FlashWhite();
// =============== 原本功能 ===============
if (phase == UnityEngine.InputSystem.TouchPhase.Began)
{
if (x == 1 && y == 5) SceneManager.LoadScene(accountSceneName);
if (x == 2 && y == 5) SceneManager.LoadScene(settingSceneName);
if (x == 3 && y == 5) Application.OpenURL("https://sthkm3.org");
}
// =============== Hold 觸發格子 (2,2) ===============
if (x == 2 && y == 2 && phase == UnityEngine.InputSystem.TouchPhase.Began)
{
// 開始長按序列
isHolding = true;
holdingCell = true;
holdTriggered = false;
holdTimer = 0f;
holdX = x;
holdY = y;
holdProgressManager.StartProgressAt(x, y, holdTarget);
}
}
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8865d87391b016443b60048183c38076
Whitespace-only changes.
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 72f889392d8c1e348bee3747b3c41b22