Rebuild the game as a single code-driven scene with a package-folder pack source

- One empty scene; App builds the canvas, safe-area layout and a shared 5x6
  Grid in code. Pages (Intro, Main, Choose, Play, Account, Settings) replace
  5 scenes, 5 prefabs and the per-cell spawner/display components.
- Packs: the game reads Rhyculator/package/ (with All files access) or the
  app folder, like a plugged-in USB stick. Zips stay where they are and are
  extracted to a cache keyed by name/size/mtime; folders are read directly.
  Scans run every second on a background thread. Old songs/ imports and inbox
  zips are migrated automatically.
- Download packs by 8-char code from the new pack website, or via
  rhyculator://pack/<code> links; opened/shared zips go into the package folder.
- Play: pause/resume/retry, auto-pause on background, combo and progress bar;
  judging and scoring unchanged. Choose page fits 9:16 screens; empty state,
  pack delete. Android back key handled everywhere.
- Slimming: removed TextMesh Pro, unused 2D/Timeline/VisualScripting/etc.
  packages and modules, scene template, unused sprites; menu theme wav (20MB)
  -> ogg (2.3MB). Build profile replaced by explicit settings in BuildAndroid.
- Tests: PackLibrary/PackReader/migration/serializer tests (39 passing).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
SahikandClaude Opus 5.5 committed 2026-10-24 14:18:54 +08:00
1 parent 6d5f66ac6a
commit ddd5fdc28b
295 files changed
+3854 -82126

No files matched your search

+226
View File
@@ -0,0 +1,226 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
// 一個畫面(主選單、選歌、遊玩…);同時只有一個,畫面內容放在 App.Top,格子是共用的
public abstract class Page
{
protected App App => App.Instance;
protected Grid Grid => App.Instance.Grid;
protected RectTransform Top => App.Instance.Top;
public virtual bool UsesGrid => true;
public virtual void Enter() { }
public virtual void Exit() { }
// 每幀:處理觸控與邏輯(在格子判定過期之前)
public virtual void Tick(List<GridTouch> touches) { }
// 每幀:格子更新後(生成新音符)
public virtual void LateTick() { }
// 返回鍵(對話框都關閉時)
public virtual void Back() => App.Go(new MainPage());
}
// 整個遊戲只有一個空場景:啟動時由這裡建立畫布、格子與第一個畫面
// 版面(畫布寬固定 1080):
// ┌ 安全區域 ┐
// │ Top │ 畫面內容(封面、標題、分數…),高度 = 剩下的空間
// │ Grid 5x6 │ 靠下;畫面太扁時縮小
// │ Footer │ UID / 版本
public class App : MonoBehaviour
{
public static App Instance { get; private set; }
public Grid Grid { get; private set; }
public RectTransform Top { get; private set; }
public RectTransform Overlay { get; private set; } // 對話框、結算
public RawImage Background { get; private set; } // 曲包影片
public AudioSource Music { get; private set; }
public GridInput Input { get; private set; }
public Page Current { get; private set; }
private const float FooterHeight = 90f;
private const float GridGap = 30f;
private const float MinTop = 460f;
private RectTransform safe;
private Text uidText;
private Rect lastSafe;
private Vector2Int lastSize;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Boot()
{
// 幀率上限 = 螢幕支援的最高更新率(Android 上 targetFrameRate = -1 代表 30fps)
QualitySettings.vSyncCount = 0;
double max = UnityEngine.Screen.currentResolution.refreshRateRatio.value;
foreach (var r in UnityEngine.Screen.resolutions)
if (r.refreshRateRatio.value > max) max = r.refreshRateRatio.value;
Application.targetFrameRate = Mathf.Max(60, Mathf.RoundToInt((float)max));
UnityEngine.Screen.sleepTimeout = SleepTimeout.NeverSleep;
PackStorage.Init();
var go = new GameObject("App");
DontDestroyOnLoad(go);
go.AddComponent<App>();
}
void Awake()
{
Instance = this;
Music = gameObject.AddComponent<AudioSource>();
Music.playOnAwake = false;
BuildEventSystem();
BuildCanvas();
Input = new GridInput(Grid);
Library.Create();
Library.Changed += () => (Current as ILibraryListener)?.LibraryChanged();
Library.DownloadRequested += code =>
{
if (!(Current is PlayPage) && !(Current is IntroPage)) Go(new ChoosePage(code));
else pendingDownload = code;
};
}
void Start()
{
Go(new IntroPage());
}
void BuildEventSystem()
{
var es = new GameObject("EventSystem", typeof(EventSystem), typeof(InputSystemUIInputModule));
DontDestroyOnLoad(es);
}
void BuildCanvas()
{
var root = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
DontDestroyOnLoad(root);
var canvas = root.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
var scaler = root.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1080, 1920);
scaler.matchWidthOrHeight = 0f;
// 黑底 + 影片背景
var bg = Ui.Image(root.transform, null, Ui.Bg);
Ui.Stretch(bg.rectTransform);
Background = Ui.Rect(root.transform, "Video").gameObject.AddComponent<RawImage>();
Background.raycastTarget = false;
Background.enabled = false;
Ui.Stretch(Background.rectTransform);
safe = Ui.Rect(root.transform, "Safe");
Top = Ui.Rect(safe, "Top");
var gridHolder = Ui.Rect(safe, "GridHolder");
Ui.Stretch(gridHolder, 0, FooterHeight);
Grid = Grid.Create(gridHolder, Ui.Font);
var footer = Ui.Rect(safe, "Footer");
footer.anchorMin = Vector2.zero;
footer.anchorMax = new Vector2(1, 0);
footer.pivot = new Vector2(0.5f, 0);
footer.sizeDelta = new Vector2(0, FooterHeight);
uidText = Ui.Label(footer, "", 30, Ui.Muted, TextAnchor.MiddleLeft);
Ui.Stretch(uidText.rectTransform, 60, 0, 60, 0);
var ver = Ui.Label(footer, "version: Alpha " + Application.version, 30, Ui.Muted, TextAnchor.MiddleRight);
Ui.Stretch(ver.rectTransform, 60, 0, 60, 0);
Overlay = Ui.Stretch(Ui.Rect(root.transform, "Overlay"));
}
// 安全區域(瀏海、導覽列)與格子大小
void Layout()
{
var size = new Vector2Int(UnityEngine.Screen.width, UnityEngine.Screen.height);
Rect sa = UnityEngine.Screen.safeArea;
if (sa == lastSafe && size == lastSize) return;
lastSafe = sa;
lastSize = size;
safe.anchorMin = new Vector2(sa.xMin / size.x, sa.yMin / size.y);
safe.anchorMax = new Vector2(sa.xMax / size.x, sa.yMax / size.y);
safe.offsetMin = safe.offsetMax = Vector2.zero;
ApplyGridLayout();
}
void ApplyGridLayout()
{
float unitsPerPixel = 1080f / Mathf.Max(1, UnityEngine.Screen.width);
float safeH = lastSafe.height * unitsPerPixel;
bool grid = Current == null || Current.UsesGrid;
Grid.gameObject.SetActive(grid);
float gridScale = Mathf.Clamp((safeH - FooterHeight - GridGap - MinTop) / Grid.Height, 0.6f, 1f);
Grid.transform.localScale = Vector3.one * gridScale;
float bottom = grid ? FooterHeight + Grid.Height * gridScale + GridGap : FooterHeight;
Top.anchorMin = Vector2.zero;
Top.anchorMax = Vector2.one;
Top.offsetMin = new Vector2(0, bottom);
Top.offsetMax = Vector2.zero;
}
private string pendingDownload; // 開場、遊玩中收到的下載連結,離開後處理
public void Go(Page page)
{
if (pendingDownload != null && page is MainPage or ChoosePage)
{
page = new ChoosePage(pendingDownload);
pendingDownload = null;
}
Dialog.CloseAll();
Current?.Exit();
foreach (Transform child in Top) Destroy(child.gameObject);
Grid.ClearAll();
Background.enabled = false;
Input.IgnoreCurrentTouches();
Current = page;
lastSize = Vector2Int.zero; // 重新套用版面(畫面可能不用格子)
Layout();
RefreshFooter();
page.Enter();
}
public void RefreshFooter() => uidText.text = "UID: " + Prefs.UidText();
void Update()
{
Layout();
// Android 的返回鍵:舊版 Input 一定會對應到 Escape;新版 Input System 在部分裝置收不到
var kb = Keyboard.current;
bool back = UnityEngine.Input.GetKeyDown(KeyCode.Escape) || (kb != null && kb.escapeKey.wasPressedThisFrame);
if (back && !Dialog.HandleBack())
Current?.Back();
var touches = Input.Poll(Dialog.AnyOpen);
Current?.Tick(touches);
if (Grid.isActiveAndEnabled) Grid.Tick();
Current?.LateTick();
}
void OnApplicationPause(bool paused)
{
if (paused) (Current as IPausable)?.OnAppPause();
}
void OnApplicationQuit() => PlayerPrefs.Save();
}
// 曲包清單改變時要更新的畫面
public interface ILibraryListener
{
void LibraryChanged();
}
// 切到背景時要暫停的畫面(遊玩)
public interface IPausable
{
void OnAppPause();
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7dababac1cb210545a1edfa37c46bed1
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 939b2bb37fbbddc4c94ddda61230a0ae
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+277
View File
@@ -0,0 +1,277 @@
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
// 帳號:登入 / 註冊 / 信箱驗證 / 個人資訊
// 登入後手機上只存 token(不存密碼);舊版存的密碼會在進入個人資訊時換成 token 並刪除
public class AccountPage : Page
{
public override bool UsesGrid => false;
private RectTransform body;
private Text error;
private bool busy;
public override void Enter()
{
App.Music.Stop();
SongClock.Stop();
var back = Ui.Button(Top, "返回", () => App.Go(new MainPage()), 40);
Ui.Place((RectTransform)back.transform, new Vector2(0, 1), new Vector2(40, -30), new Vector2(200, 100));
if (Prefs.LoggedIn) ShowInfo();
else ShowLogin();
}
// 換一個面板:清掉內容,回傳新的 Column
RectTransform Panel(string title)
{
if (body != null) Object.Destroy(body.parent.parent.gameObject);
var holder = Ui.Stretch(Ui.Rect(Top, "Panel"), 60, 0, 60, 150);
body = Ui.Scroll(holder, 28, 10);
var t = Ui.Label(body, title, 64, Color.white);
t.fontStyle = FontStyle.Bold;
Ui.Height(t, 110);
error = Ui.Label(body, "", 36, Ui.Danger);
error.transform.SetAsLastSibling();
return body;
}
InputField Field(string label, string placeholder, InputField.ContentType type = InputField.ContentType.Standard)
{
Ui.Label(body, label, 36, Ui.Muted, TextAnchor.MiddleLeft);
return Ui.Height(Ui.Input(body, placeholder, type), 120);
}
Button Action(string label, System.Action onClick, bool primary = false)
=> Ui.Height(Ui.Button(body, label, () => { if (!busy) onClick(); }, 46, primary), 120);
void ShowError(string msg)
{
error.text = msg;
error.transform.SetAsLastSibling();
}
// ---------- 登入 ----------
void ShowLogin()
{
Panel("登入帳號");
var id = Field("ID", "輸入你的 ID");
var pw = Field("密碼", "輸入你的密碼", InputField.ContentType.Password);
Action("登入", () => App.StartCoroutine(Login(id.text.Trim(), pw.text)), primary: true);
Action("註冊帳號", ShowRegister);
Ui.Label(body, "曲包網站也使用同一組帳號登入", 32, Ui.Muted);
}
IEnumerator Login(string name, string password)
{
if (name == "" || password == "") { ShowError("請輸入 ID 與密碼"); yield break; }
busy = true;
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "login", ["name"] = name, ["password"] = password }, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error == "cant_find_name" || r.error == "password_wrong" ? "ID 或密碼錯誤" : "登入失敗:" + r.error);
yield break;
}
SaveLogin(r.Int("uid"), r.Str("token"), r.Str("email"));
ShowInfo();
}
static void SaveLogin(int uid, string token, string email)
{
PlayerPrefs.SetInt(Prefs.Uid, uid);
PlayerPrefs.SetString(Prefs.Token, token);
PlayerPrefs.SetString(Prefs.Email, email);
PlayerPrefs.DeleteKey(Prefs.LegacyPassword);
PlayerPrefs.Save();
}
// ---------- 註冊 ----------
void ShowRegister()
{
Panel("註冊帳號");
var email = Field("電子信箱", "輸入你的信箱", InputField.ContentType.EmailAddress);
var id = Field("ID", "自訂一個獨一無二 ID");
var pw = Field("密碼", "至少 6 位,包含英文與數字", InputField.ContentType.Password);
var pw2 = Field("確認密碼", "再輸入一次密碼", InputField.ContentType.Password);
Action("送出", () => App.StartCoroutine(Register(email.text.Trim(), id.text.Trim(), pw.text, pw2.text)), primary: true);
Action("已有帳號,登入", ShowLogin);
}
IEnumerator Register(string email, string id, string password, string password2)
{
string problem =
!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$") ? "請輸入有效的電子郵件地址" :
id.Length < 4 ? "ID 長度不足 4 位" :
id.Length > 30 ? "ID 最多 30 字" :
password.Length < 6 ? "密碼長度不足 6 位" :
!Regex.IsMatch(password, @"^(?=.*[a-zA-Z])(?=.*\d).+$") ? "密碼需包含英文與數字" :
password != password2 ? "兩次輸入密碼不一致" : null;
if (problem != null) { ShowError(problem); yield break; }
busy = true;
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "create_user", ["email"] = email, ["name"] = id, ["password"] = password }, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error == "email_exists" ? "信箱已被註冊" : r.error == "name_exists" ? "ID 已被使用" : "建立帳號失敗:" + r.error);
yield break;
}
SaveLogin(r.Int("uid"), r.Str("token"), email);
App.RefreshFooter();
yield return SendCode(email);
}
// ---------- 信箱驗證 ----------
IEnumerator SendCode(string email)
{
busy = true;
Api.Response r = null;
yield return Api.Verify(new Dictionary<string, object> { ["game"] = "lunchpad", ["email"] = email, ["code"] = "", ["password"] = "" }, x => r = x);
busy = false;
if (r.error != null && r.error != "too_many_requests")
{
ShowError("驗證信寄送失敗:" + r.error);
yield break;
}
ShowVerify(email);
if (r.error == "too_many_requests") ShowError("驗證信已寄出,請稍候再重新發送");
}
void ShowVerify(string email)
{
Panel("驗證信箱");
Ui.Label(body, $"驗證信已寄到 {email}\n請檢查收件匣或垃圾郵件,驗證碼 5 分鐘內有效", 36, Ui.Muted);
var code = Field("驗證碼", "6 位數字", InputField.ContentType.IntegerNumber);
code.characterLimit = 6;
Action("驗證", () => App.StartCoroutine(Verify(email, code.text.Trim())), primary: true);
Action("重新發送", () => App.StartCoroutine(SendCode(email)));
Action("稍後再驗證", ShowInfo);
}
IEnumerator Verify(string email, string code)
{
busy = true;
Api.Response r = null;
yield return Api.Verify(new Dictionary<string, object>
{
["game"] = "lunchpad", ["email"] = email, ["code"] = code, ["password"] = Credential(),
}, x => r = x);
busy = false;
if (r.error != null)
{
ShowError(r.error switch
{
"wrong_code" => "驗證碼錯誤",
"expired" => "驗證碼已過期,請重新發送",
"not_requested" => "請先發送驗證碼",
_ => "驗證失敗:" + r.error,
});
yield break;
}
Toast.Show("信箱驗證完成");
ShowInfo();
}
// 驗證用憑證:Token 優先,舊版才用密碼
static string Credential()
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
return token != "" ? token : PlayerPrefs.GetString(Prefs.LegacyPassword, "");
}
// ---------- 個人資訊 ----------
void ShowInfo()
{
App.RefreshFooter();
Panel("個人資訊");
var info = Ui.Label(body, "讀取中…", 40, Ui.TextColor, TextAnchor.UpperLeft);
info.lineSpacing = 1.3f;
var verifyButton = Action("驗證信箱", () => App.StartCoroutine(SendCode(PlayerPrefs.GetString(Prefs.Email, ""))));
verifyButton.gameObject.SetActive(false);
Action("重新整理", ShowInfo);
Action("登出", LogOut);
App.StartCoroutine(LoadInfo(info, verifyButton));
}
IEnumerator LoadInfo(Text info, Button verifyButton)
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
string password = PlayerPrefs.GetString(Prefs.LegacyPassword, "");
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "person_info", ["uid"] = Prefs.UserId, ["token"] = token,
["password"] = token == "" ? password : null,
}, x => r = x);
if (info == null) yield break; // 已經換面板
if (r.error != null)
{
info.text = r.error == "auth_failed" ? "登入已過期,請重新登入" : "載入失敗:" + r.error;
if (r.error == "auth_failed") ClearLogin();
yield break;
}
PlayerPrefs.SetString(Prefs.Name, r.Str("name"));
PlayerPrefs.SetString(Prefs.CreateTime, r.Str("create_time"));
PlayerPrefs.SetString(Prefs.AccountType, r.Str("account_type"));
PlayerPrefs.SetString(Prefs.Email, r.Str("email"));
PlayerPrefs.SetInt(Prefs.EmailVerified, r.Int("email_v"));
PlayerPrefs.Save();
App.RefreshFooter();
// 舊版只存了密碼:重新登入換取 Token,並刪除手機上的密碼
if (token == "" && password != "")
{
Api.Response login = null;
yield return Api.Game(new Dictionary<string, object> { ["request"] = "login", ["name"] = r.Str("name"), ["password"] = password }, x => login = x);
if (login.error == null && login.Str("token") != "")
SaveLogin(Prefs.UserId, login.Str("token"), r.Str("email"));
}
string type = r.Str("account_type") switch { "R" => "玩家", "A" => "Alpha 測試", "B" => "Beta 測試", "D" => "開發者", var t => t };
bool verified = r.Int("email_v") == 1;
info.text =
$"使用者號碼 {Prefs.UidText()}\n" +
$"顯示名稱  {r.Str("name")}\n" +
$"帳號類型  {type}\n" +
$"建立日期  {r.Str("create_time")}\n" +
$"電子信箱  {MaskEmail(r.Str("email"))} {(verified ? "<color=#7DD67D>已驗證</color>" : "<color=#FF6060>未驗證</color>")}";
verifyButton.gameObject.SetActive(!verified);
}
static string MaskEmail(string email)
{
int at = email.IndexOf('@');
return at < 0 ? email : email.Substring(0, Mathf.Min(2, at)) + "*****" + email.Substring(at);
}
void LogOut()
{
string token = PlayerPrefs.GetString(Prefs.Token, "");
if (token != "")
App.StartCoroutine(Api.Game(new Dictionary<string, object> { ["request"] = "logout", ["token"] = token }, _ => { }));
ClearLogin();
ShowLogin();
}
void ClearLogin()
{
foreach (var k in new[] { Prefs.Token, Prefs.Uid, Prefs.LegacyPassword, Prefs.Name, Prefs.AccountType, Prefs.CreateTime, Prefs.EmailVerified })
PlayerPrefs.DeleteKey(k);
PlayerPrefs.Save();
App.RefreshFooter();
}
public override void Back() => App.Go(new MainPage());
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2095ee3cdc687d1469892a47e49f4777
+393
View File
@@ -0,0 +1,393 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
// 選歌:左右切換曲包、選難度、看個人最高分 / 排行榜、開始
// 格子:(0,5) 分數 (1..3,5) 難度 (4,5) 排行 | (2,3) 目前難度 | (1,2) 上一首 (2,2) 開始 (3,2) 下一首
// 上方:返回、代碼下載、管理(刪除曲包、資料夾位置)
public class ChoosePage : Page, ILibraryListener
{
private readonly string downloadCode; // 由網站連結(rhyculator://pack/<code>)開啟時自動下載
private IReadOnlyList<SongInfo> songs;
private int index, level;
private string selectId; // 下載完成後要選的曲包
private RectTransform songView, emptyView;
private RawImage cover;
private Text nameText, artistText, countText;
private readonly Dictionary<string, Texture2D> covers = new Dictionary<string, Texture2D>();
private AudioClip previewClip;
private int previewGen;
private float previewStart, previewEnd;
private Dialog download;
public ChoosePage(string downloadCode = null)
{
this.downloadCode = downloadCode;
}
private SongInfo Song => songs != null && songs.Count > 0 ? songs[index] : null;
public override void Enter()
{
App.Music.Stop();
SongClock.Stop();
var back = Ui.Button(Top, "返回", () => App.Go(new MainPage()), 40);
Ui.Place((RectTransform)back.transform, new Vector2(0, 1), new Vector2(40, -30), new Vector2(200, 100));
var dl = Ui.Button(Top, "代碼下載", () => ShowDownload(""), 40);
Ui.Place((RectTransform)dl.transform, new Vector2(1, 1), new Vector2(-260, -30), new Vector2(260, 100));
var more = Ui.Button(Top, "管理", ShowManage, 40);
Ui.Place((RectTransform)more.transform, new Vector2(1, 1), new Vector2(-40, -30), new Vector2(200, 100));
BuildSongView();
BuildEmptyView();
level = PlayerPrefs.GetInt(Prefs.Level, 1);
LibraryChanged();
if (!string.IsNullOrEmpty(downloadCode)) ShowDownload(downloadCode, autoStart: true);
}
void BuildSongView()
{
songView = Ui.Stretch(Ui.Rect(Top, "Song"));
countText = Ui.Label(songView, "", 34, Ui.Muted);
Ui.Place(countText.rectTransform, new Vector2(0.5f, 1), new Vector2(-60, -55), new Vector2(300, 50));
// 封面:在按鈕列與文字之間,保持正方形
var box = Ui.Stretch(Ui.Rect(songView, "CoverBox"), 40, 150, 40, 160);
cover = Ui.Rect(box, "Cover").gameObject.AddComponent<RawImage>();
cover.raycastTarget = false;
var fit = cover.gameObject.AddComponent<AspectRatioFitter>();
fit.aspectMode = AspectRatioFitter.AspectMode.FitInParent;
fit.aspectRatio = 1;
nameText = Ui.Label(songView, "", 50, Color.white);
nameText.fontStyle = FontStyle.Bold;
nameText.horizontalOverflow = HorizontalWrapMode.Wrap;
nameText.resizeTextForBestFit = true;
nameText.resizeTextMinSize = 30;
nameText.resizeTextMaxSize = 50;
nameText.verticalOverflow = VerticalWrapMode.Truncate;
Ui.Place(nameText.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 70), new Vector2(1000, 75));
artistText = Ui.Label(songView, "", 36, Ui.Muted);
Ui.Place(artistText.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 15), new Vector2(1000, 55));
}
void BuildEmptyView()
{
emptyView = Ui.Stretch(Ui.Rect(Top, "Empty"), 60, 0, 60, 150);
var col = Ui.Column(emptyView, 30);
Ui.Stretch(col);
col.GetComponent<VerticalLayoutGroup>().childAlignment = TextAnchor.MiddleCenter;
Ui.Label(col, "還沒有任何曲包", 56, Color.white);
Ui.Label(col, $"把曲包 .zip 放進\n<color=#FF66C4>{DisplayPath(PackStorage.PackageDir)}</color>\n或輸入曲包網站上的代碼下載", 36, Ui.Muted);
var row = Ui.Height(Ui.Row(col, 30), 110);
Ui.Button(row, "輸入代碼", () => ShowDownload(""), 40, primary: true);
Ui.Button(row, "曲包網站", () => Application.OpenURL(ServerConfig.GameServerUrl + "/"), 40);
}
// 手機路徑顯示成使用者在檔案管理員看到的樣子
public static string DisplayPath(string path)
{
const string sd = "/storage/emulated/0/";
return path.StartsWith(sd) ? "內部儲存空間/" + path.Substring(sd.Length) : path;
}
public void LibraryChanged()
{
string keep = selectId ?? Song?.id ?? Library.Current?.id;
songs = Library.Songs;
index = 0;
for (int i = 0; i < songs.Count; i++)
if (songs[i].id == keep) index = i;
if (selectId != null && Library.Find(selectId) != null) selectId = null;
ShowSong();
}
void ShowSong()
{
var song = Song;
songView.gameObject.SetActive(song != null);
emptyView.gameObject.SetActive(song == null && Library.Loaded);
Grid.ClearAll();
StopPreview();
if (song == null) return;
Library.Current = song;
if (!song.HasLevel(level)) level = song.FirstLevel();
PlayerPrefs.SetInt(Prefs.Level, level);
countText.text = songs.Count > 1 ? $"{index + 1} / {songs.Count}" : "";
nameText.text = song.name;
artistText.text = string.IsNullOrEmpty(song.charter) ? song.artist : $"{song.artist} · 譜面 {song.charter}";
cover.texture = LoadCover(song);
cover.enabled = cover.texture != null;
bool many = songs.Count > 1;
Grid.SetIcon(1, 2, many ? Sprites.Get("ArrowLeft") : null);
Grid.SetIcon(3, 2, many ? Sprites.Get("ArrowRight") : null);
Grid.SetIcon(2, 2, Sprites.Get("Start"));
Grid.SetIcon(0, 5, Sprites.Get("Score"));
Grid.SetIcon(4, 5, Sprites.Get("Rank"));
for (int l = 1; l <= SongInfo.LevelCount; l++)
Grid.SetLabel(l, 5, song.HasLevel(l) ? LevelText(song, l) : null, Ui.LevelColors[l]);
ShowLevel();
App.StartCoroutine(PlayPreview(song));
}
void ShowLevel()
{
Grid.SetLabel(2, 3, LevelText(Song, level), Ui.LevelColors[level], 0.6f);
}
static string LevelText(SongInfo song, int l) => song.levelNum[l] > 0 ? song.levelNum[l].ToString() : "?";
Texture2D LoadCover(SongInfo song)
{
string key = song.dir;
if (covers.TryGetValue(key, out var cached)) return cached;
Texture2D tex = null;
try
{
if (File.Exists(song.ImagePath))
{
tex = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (!tex.LoadImage(File.ReadAllBytes(song.ImagePath)))
{
Object.Destroy(tex);
tex = null;
}
}
}
catch (System.Exception e)
{
Debug.LogWarning($"[Choose] 封面讀取失敗 {song.id}:{e.Message}");
}
covers[key] = tex;
return tex;
}
// ---------- 試聽 ----------
IEnumerator PlayPreview(SongInfo song)
{
int gen = ++previewGen;
yield return new WaitForSecondsRealtime(0.25f); // 快速切換時不必每首都載入
string path = song.MusicPath;
if (gen != previewGen || path == null) yield break;
AudioClip clip;
using (var www = PlayPage.LoadAudio(path))
{
yield return www.SendWebRequest();
if (gen != previewGen) yield break;
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("[Choose] 試聽載入失敗:" + www.error);
yield break;
}
clip = DownloadHandlerAudioClip.GetContent(www);
}
if (clip == null) yield break;
StopPreview(destroyOnly: true);
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;
var music = App.Music;
music.clip = clip;
music.loop = true;
music.time = previewStart;
music.Play();
}
void StopPreview(bool destroyOnly = false)
{
if (!destroyOnly) previewGen++;
App.Music.Stop();
if (previewClip != null)
{
if (App.Music.clip == previewClip) App.Music.clip = null;
Object.Destroy(previewClip);
previewClip = null;
}
}
// ---------- 操作 ----------
public override void Tick(List<GridTouch> touches)
{
// 試聽片段循環
var music = App.Music;
if (previewClip != null && music.isPlaying && previewEnd > previewStart && music.time >= previewEnd)
music.time = previewStart;
foreach (var t in touches)
{
if (!t.OnCell) continue;
Grid.Flash(t.x, t.y, CellFlash.White);
if (t.began) Tap(t.x, t.y);
}
}
void Tap(int x, int y)
{
var song = Song;
if (song == null) return;
if (y == 2 && (x == 1 || x == 3) && songs.Count > 1)
{
index = (index + (x == 1 ? songs.Count - 1 : 1)) % songs.Count;
ShowSong();
}
else if (y == 5 && x >= 1 && x <= SongInfo.LevelCount && song.HasLevel(x))
{
level = x;
PlayerPrefs.SetInt(Prefs.Level, level);
ShowLevel();
}
else if (y == 5 && x == 0) App.StartCoroutine(ShowScore(song, level));
else if (y == 5 && x == 4) App.StartCoroutine(ShowRank(song, level));
else if (y == 2 && x == 2)
{
Grid.Flash(x, y, CellFlash.Blue);
App.Go(new PlayPage(song, level));
}
}
IEnumerator ShowScore(SongInfo song, int lv)
{
if (!Prefs.LoggedIn)
{
Info("個人最高分", "登入後才會記錄成績");
yield break;
}
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "score", ["uid"] = Prefs.UserId, ["song"] = song.id, ["level"] = lv,
}, x => r = x);
Info($"個人最高分 · {SongInfo.LevelName(lv)}", r.error ?? r.Int("score").ToString());
}
IEnumerator ShowRank(SongInfo song, int lv)
{
Api.Response r = null;
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "rank", ["song"] = song.id, ["level"] = lv,
}, x => r = x);
if (r.error != null)
{
Info("排行榜", r.error);
yield break;
}
// 伺服器以 null 表示該名次無人
var sb = new System.Text.StringBuilder();
for (int i = 1; i <= 5; i++)
{
string name = r.Str($"name_{i}");
if (string.IsNullOrEmpty(name)) break;
sb.Append($"{i}. {name} <color=#FFFFFF>{r.Int($"score_{i}")}</color>\n");
}
Info($"排行榜 · {SongInfo.LevelName(lv)}", sb.Length > 0 ? sb.ToString().TrimEnd() : "尚無紀錄");
}
void Info(string title, string text)
{
var d = new Dialog(App.Overlay, title, text);
d.message.fontSize = 48;
d.AddClose("關閉");
}
// ---------- 下載 ----------
void ShowDownload(string code, bool autoStart = false)
{
if (download != null && download.IsOpen) download.Close();
var d = download = new Dialog(App.Overlay, "以代碼下載曲包", "輸入曲包網站上的 8 碼代碼");
var input = Ui.Height(Ui.Input(d.body, "例如 e4hfbqcg", UnityEngine.UI.InputField.ContentType.Alphanumeric, 56), 120);
input.characterLimit = 8;
input.text = code;
var status = Ui.Label(d.body, "", 38, Ui.Muted);
Button go = null;
d.AddClose("取消");
go = d.AddButton("下載", () => App.StartCoroutine(RunDownload(d, input, status, go)), primary: true);
if (autoStart && code.Length > 0) App.StartCoroutine(RunDownload(d, input, status, go));
}
IEnumerator RunDownload(Dialog d, InputField input, Text status, Button go)
{
string code = input.text.Trim().ToLowerInvariant();
if (code.Length != 8)
{
status.text = "<color=#FF6060>代碼是 8 個英數字</color>";
yield break;
}
go.interactable = false;
input.interactable = false;
d.cancellable = false;
string error = null, title = null;
yield return Api.DownloadPack(code,
p => status.text = $"下載中… {p * 100:0}%",
(e, t) => { error = e; title = t; });
d.cancellable = true;
go.interactable = true;
input.interactable = true;
if (error != null)
{
status.text = $"<color=#FF6060>{error}</color>";
yield break;
}
selectId = code;
d.Close();
Toast.Show($"已下載「{title}」");
}
// ---------- 管理 ----------
void ShowManage()
{
var song = Song;
var d = new Dialog(App.Overlay, "曲包管理",
$"曲包資料夾:\n<color=#FF66C4>{DisplayPath(PackStorage.PackageDir)}</color>\n共 {songs.Count} 個曲包");
if (song != null)
{
Ui.Height(Ui.Button(d.body, $"刪除「{song.name}」", () => ConfirmDelete(d, song), 40), 110);
}
Ui.Height(Ui.Button(d.body, "開啟曲包網站", () => Application.OpenURL(ServerConfig.GameServerUrl + "/"), 40), 110);
d.AddClose("關閉");
}
void ConfirmDelete(Dialog manage, SongInfo song)
{
var d = new Dialog(App.Overlay, "刪除曲包?", $"「{song.name}」\n{Path.GetFileName(song.source)}\n會從曲包資料夾刪除");
d.AddClose("取消");
d.AddClose("刪除", () =>
{
manage.Close();
if (PackStorage.DeleteSource(song))
{
Toast.Show($"已刪除「{song.name}」");
Library.Rescan();
}
else Toast.Show("刪除失敗");
}, primary: true);
}
public override void Back() => App.Go(new MainPage());
public override void Exit()
{
StopPreview();
foreach (var t in covers.Values)
if (t != null) Object.Destroy(t);
covers.Clear();
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9ff06c2deef0cee4ca0c62902b0d3ced
+96
View File
@@ -0,0 +1,96 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 開場:STHKM3 → 戴上耳機 → 閃爍警告;點擊跳到下一張
// 第一次開啟且還沒有儲存權限時,結束後詢問是否使用手機根目錄的 Rhyculator/package
public class IntroPage : Page
{
private static readonly float[] Durations = { 1.885f, 1.846f, 1.846f };
public override bool UsesGrid => false;
private readonly List<GameObject> cards = new List<GameObject>();
private int index = -1;
private float nextAt;
public override void Enter()
{
cards.Add(ImageCard("Start_1", null));
cards.Add(ImageCard("Start_2", "戴上耳機以獲得最佳體驗"));
cards.Add(TextCard("本遊戲包含大量閃爍特效\n請斟酌遊玩"));
Next();
}
GameObject ImageCard(string sprite, string caption)
{
var card = Ui.Stretch(Ui.Rect(Top, sprite));
var img = Ui.Image(card, Sprites.Get(sprite), Color.white);
img.preserveAspect = true;
Ui.Place(img.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, caption != null ? 120 : 0), new Vector2(1080, 720));
if (caption != null)
{
var t = Ui.Label(card, caption, 64, Color.white);
Ui.Place(t.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -220), new Vector2(1000, 120));
}
card.gameObject.SetActive(false);
return card.gameObject;
}
GameObject TextCard(string text)
{
var t = Ui.Label(Top, text, 64, Color.white);
t.lineSpacing = 1.3f;
Ui.Stretch(t.rectTransform, 40, 0, 40, 0);
t.gameObject.SetActive(false);
return t.gameObject;
}
void Next()
{
if (index >= 0) cards[index].SetActive(false);
index++;
if (index >= cards.Count)
{
Finish();
return;
}
cards[index].SetActive(true);
nextAt = -1; // 從第一個畫出來的幀開始計時(剛啟動的前幾幀很慢)
}
public override void Tick(List<GridTouch> touches)
{
if (index >= cards.Count) return;
if (nextAt < 0)
{
if (Time.unscaledDeltaTime < 0.1f) nextAt = Time.unscaledTime + Durations[index];
return;
}
if (Time.unscaledTime >= nextAt || GridInput.AnyNewTap()) Next();
}
public override void Back() => Next();
void Finish()
{
if (!PackStorage.SupportsShared || PackStorage.HasSharedAccess() || PlayerPrefs.GetInt(Prefs.StorageAsked, 0) == 1)
{
App.Go(new MainPage());
return;
}
PlayerPrefs.SetInt(Prefs.StorageAsked, 1);
var d = new Dialog(App.Overlay, "曲包資料夾",
"允許「所有檔案存取權」後,曲包會放在手機的\n<color=#FF66C4>Rhyculator/package</color>\n" +
"接上電腦或用檔案管理員就能直接放入 .zip 曲包,像插上隨身碟一樣。\n\n" +
"不允許也可以玩,曲包會放在 app 自己的資料夾。之後可在設定裡更改。");
d.cancellable = false;
d.AddClose("先不要", () => App.Go(new MainPage()));
d.AddClose("前往授權", () =>
{
PackStorage.RequestSharedAccess();
App.Go(new MainPage());
}, primary: true);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5a78ae78e1cfbcc4c9a4917bdf846ae2
+148
View File
@@ -0,0 +1,148 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 主選單:長按中間開始;上排帳號 / 設定 / 曲包網站;背景播放主題曲與它的譜面
// 點背景音符會顯示 Early / Late 毫秒數(可當延遲校正參考)
public class MainPage : Page, ILibraryListener
{
private const float HoldSeconds = 1f;
private const int HoldX = 2, HoldY = 2;
private ChartPlayer chart;
private Text info, offset;
private int holdFinger = -1;
private float holdStart;
public override void Enter()
{
var title = Ui.Label(Top, "Rhyculator", 140, Color.white);
title.fontStyle = FontStyle.Bold;
Ui.Place(title.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, 60), new Vector2(1080, 200));
info = Ui.Label(Top, "", 40, Ui.Muted);
Ui.Place(info.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -70), new Vector2(1000, 60));
offset = Ui.Label(Top, "", 44, Ui.Accent);
Ui.Place(offset.rectTransform, new Vector2(0.5f, 0f), new Vector2(0, 10), new Vector2(1000, 70));
LibraryChanged();
Grid.SetIcon(1, 5, Sprites.Get("Display account"));
Grid.SetIcon(2, 5, Sprites.Get("Display setting"));
Grid.SetIcon(3, 5, Sprites.Get("Display global"));
Grid.SetIcon(HoldX, HoldY, Sprites.Get("HoldStart"));
Grid.SetIcon(1, 2, Sprites.Get("ArrowRight"));
Grid.SetIcon(3, 2, Sprites.Get("ArrowLeft"));
Grid.SetIcon(2, 1, Sprites.Get("ArrowUp"));
Grid.SetIcon(2, 3, Sprites.Get("ArrowDown"));
StartTheme();
}
public void LibraryChanged()
{
int n = Library.Songs.Count;
info.text = !Library.Loaded ? "讀取曲包中…" : n > 0 ? $"已載入 {n} 個曲包 長按中間開始" : "還沒有曲包:長按中間開始後可輸入代碼下載";
}
void StartTheme()
{
var music = App.Music;
var clip = Resources.Load<AudioClip>("MainTheme/music");
var sheet = Resources.Load<TextAsset>("MainTheme/sheet");
if (clip == null || sheet == null) return;
try { chart = new ChartPlayer(ChartLoader.Parse(sheet.text, 0, out _)); }
catch (System.Exception e) { Debug.LogWarning("[Main] 主題譜面讀取失敗:" + e.Message); }
// 從帳號 / 設定回來時主題曲還在播:接著播,時鐘對齊目前位置
if (music.clip == clip && music.isPlaying)
{
double start = AudioSettings.dspTime - music.time;
SongClock.Begin(start);
chart?.Seek(music.time);
return;
}
music.Stop();
music.clip = clip;
music.loop = false;
double dspStart = AudioSettings.dspTime + 0.5;
music.PlayScheduled(dspStart);
SongClock.Begin(dspStart);
chart?.Seek(0);
}
public override void Tick(List<GridTouch> touches)
{
// 主題曲播完:重新開始
if (App.Music.clip != null && !App.Music.isPlaying && SongClock.Running && SongClock.Now > App.Music.clip.length)
StartTheme();
foreach (var t in touches)
{
if (t.ended)
{
if (t.fingerId == holdFinger) StopHold();
continue;
}
if (!t.OnCell) continue;
if (!t.began)
{
Grid.Flash(t.x, t.y, CellFlash.White);
continue;
}
if (t.x == HoldX && t.y == HoldY && holdFinger < 0)
{
holdFinger = t.fingerId;
holdStart = Time.unscaledTime;
Grid.StartRing(t.x, t.y, HoldSeconds);
Grid.Flash(t.x, t.y, CellFlash.Blue);
}
else if (t.y == 5 && t.x == 1) App.Go(new AccountPage());
else if (t.y == 5 && t.x == 2) App.Go(new SettingsPage());
else if (t.y == 5 && t.x == 3) Application.OpenURL(ServerConfig.GameServerUrl + "/");
else JudgeBackground(t);
}
if (holdFinger >= 0 && Time.unscaledTime - holdStart >= HoldSeconds)
{
holdFinger = -1;
App.Go(new ChoosePage());
}
}
public override void LateTick()
{
if (chart != null && SongClock.Running) chart.Tick(Grid, SongClock.Now);
}
void StopHold()
{
holdFinger = -1;
Grid.StopRing(HoldX, HoldY);
}
void JudgeBackground(GridTouch t)
{
if (!Grid.HasNote(t.x, t.y)) return;
double delta = SongClock.Now - t.pressAge - Grid.HitTime(t.x, t.y);
Judgement j = NoteJudge.Evaluate(delta);
if (j == Judgement.None || j == Judgement.Miss) return;
Grid.Flash(t.x, t.y, PlayPage.FlashFor(j));
Grid.ClearNote(t.x, t.y);
int ms = (int)System.Math.Round(delta * 1000);
offset.text = (ms < 0 ? "Early " : "Late ") + System.Math.Abs(ms) + "ms";
}
public override void Back()
{
var d = new Dialog(App.Overlay, "離開遊戲?");
d.AddClose("取消");
d.AddClose("離開", Application.Quit, primary: true);
}
public override void Exit()
{
Grid.StopRing(HoldX, HoldY);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 04825755a7bcb6243909e4a5e77d4a2f
+438
View File
@@ -0,0 +1,438 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;
// 遊玩:載入曲包的音樂、譜面與影片,判定、計分,結束後上傳成績並顯示結算
// 音樂用 PlayScheduled 排在 DSP 時鐘上,音符時間與音訊同一個時間基準,不會累積誤差
public class PlayPage : Page, IPausable
{
private const double LeadIn = 1.0; // 音樂開始前的準備時間,讓開頭的音符也有完整的出現動畫
private const double ResumeRewind = 1.0; // 暫停後接續時倒回的秒數
private const int HoldFullScore = 212;
private const int SlideScore = 106;
private const float VideoAlpha = 0.4f;
private readonly SongInfo song;
private readonly int level;
private enum State { Loading, Playing, Paused, Finished }
private State state = State.Loading;
private ChartPlayer chart;
private AudioClip clip;
private VideoPlayer video;
private RenderTexture videoTexture;
private bool videoStarted;
private readonly PlayResult result = new PlayResult();
private Text scoreText, comboText;
private RectTransform progress;
private Button pauseButton;
private Dialog pauseDialog;
private GameObject overlay;
// 按住中的 Hold(可同時多個)
private class ActiveHold
{
public int x, y, fingerId;
public double hitTime, duration;
public Judgement head;
}
private readonly List<ActiveHold> holds = new List<ActiveHold>();
public PlayPage(SongInfo song, int level)
{
this.song = song;
this.level = level;
}
public override void Enter()
{
Library.Paused = true;
App.Music.Stop();
SongClock.Stop();
Grid.NoteExpired += OnExpired;
var title = Ui.Label(Top, $"{song.name} <color=#{ColorUtility.ToHtmlStringRGB(Ui.LevelColors[level])}>{SongInfo.LevelName(level).ToUpper()} {song.levelNum[level]}</color>", 34, Ui.Muted);
title.horizontalOverflow = HorizontalWrapMode.Overflow;
Ui.Place(title.rectTransform, new Vector2(0.5f, 1), new Vector2(0, -50), new Vector2(760, 60));
pauseButton = Ui.Button(Top, "II", Pause, 44);
Ui.Place((RectTransform)pauseButton.transform, new Vector2(1, 1), new Vector2(-40, -30), new Vector2(120, 100));
scoreText = Ui.Label(Top, "載入中…", 120, Color.white);
scoreText.fontStyle = FontStyle.Bold;
Ui.Place(scoreText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, 0), new Vector2(1000, 160));
comboText = Ui.Label(Top, "", 44, Ui.Accent);
Ui.Place(comboText.rectTransform, new Vector2(0.5f, 0.5f), new Vector2(0, -110), new Vector2(1000, 60));
var bar = Ui.Image(Top, null, new Color(1, 1, 1, 0.12f));
Ui.Place(bar.rectTransform, new Vector2(0.5f, 0), new Vector2(0, 0), new Vector2(980, 8));
progress = Ui.Image(bar.transform, null, Ui.Accent).rectTransform;
progress.anchorMin = Vector2.zero;
progress.anchorMax = new Vector2(0, 1);
progress.offsetMin = progress.offsetMax = Vector2.zero;
App.StartCoroutine(Load());
}
// ---------- 載入 ----------
IEnumerator Load()
{
try
{
chart = new ChartPlayer(ChartLoader.LoadFile(song.ChartPath(level), song.offsetMs, out int skipped));
if (skipped > 0) Debug.LogWarning($"[Play] {song.id} 略過 {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 (state != State.Loading) yield break; // 載入中就離開了
if (www.result != UnityWebRequest.Result.Success) { Fail("音樂載入失敗:" + www.error); yield break; }
clip = DownloadHandlerAudioClip.GetContent(www);
}
if (clip == null || clip.length <= 0f) { Fail("音樂無法解碼"); yield break; }
if (Prefs.GetBool(Prefs.VideoBackground, true) && song.VideoPath != null) SetupVideo(song.VideoPath);
var music = App.Music;
music.clip = clip;
music.loop = false;
music.time = 0;
double start = AudioSettings.dspTime + LeadIn;
music.PlayScheduled(start);
SongClock.Begin(start);
state = State.Playing;
scoreText.text = "0";
Debug.Log($"[Play] {song.id} {SongInfo.LevelName(level)}: {chart.Count} events, clip {clip.length:0.0}s");
}
void Fail(string message)
{
state = State.Finished;
Toast.Show(message);
App.Go(new ChoosePage());
}
// 本機檔案 → UnityWebRequest 用的 file:// 網址(處理空白與 Windows 路徑)
public static string FileUrl(string path) => new Uri(Path.GetFullPath(path)).AbsoluteUri;
// ogg / mp3 保持壓縮(整首不解壓,省記憶體);wav 開壓縮模式在 Android 上會讓主執行緒卡死,直接載入
public static UnityWebRequest LoadAudio(string path)
{
AudioType type = Path.GetExtension(path).ToLowerInvariant() switch
{
".ogg" => AudioType.OGGVORBIS,
".mp3" => AudioType.MPEG,
_ => AudioType.WAV,
};
var www = UnityWebRequestMultimedia.GetAudioClip(FileUrl(path), type);
((DownloadHandlerAudioClip)www.downloadHandler).compressed = type != AudioType.WAV;
return www;
}
// 曲包的 video.mp4:畫在格子後方當背景,聲音一律用 music 檔
void SetupVideo(string path)
{
var go = new GameObject("PackVideo");
go.transform.SetParent(App.transform, false);
video = go.AddComponent<VideoPlayer>();
video.playOnAwake = false;
video.source = VideoSource.Url;
video.url = FileUrl(path);
video.renderMode = VideoRenderMode.RenderTexture;
video.audioOutputMode = VideoAudioOutputMode.None;
video.isLooping = false;
video.skipOnDrop = true;
video.prepareCompleted += vp =>
{
videoTexture = new RenderTexture((int)vp.width, (int)vp.height, 0);
vp.targetTexture = videoTexture;
var bg = App.Background;
bg.texture = videoTexture;
bg.color = new Color(1, 1, 1, VideoAlpha);
var fit = bg.GetComponent<AspectRatioFitter>() ?? bg.gameObject.AddComponent<AspectRatioFitter>();
fit.aspectMode = AspectRatioFitter.AspectMode.EnvelopeParent;
fit.aspectRatio = (float)vp.width / Mathf.Max(1, vp.height);
};
video.Prepare();
}
// ---------- 遊玩 ----------
public override void Tick(List<GridTouch> touches)
{
if (state != State.Playing) return;
double now = SongClock.Now;
if (video != null && !videoStarted && now >= 0 && video.isPrepared)
{
if (now > 0.05) video.time = now; // 準備得比音樂慢:從目前位置接上
video.Play();
App.Background.enabled = true;
videoStarted = true;
}
// 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 touches)
{
if (t.ended)
{
var h = holds.Find(a => a.fingerId == t.fingerId);
if (h != null) FinishHold(h, now);
continue;
}
if (!t.OnCell) continue;
if (!Grid.HasNote(t.x, t.y))
{
Grid.Flash(t.x, t.y, CellFlash.White); // 空按也亮白色(不覆蓋判定色)
continue;
}
// 按下的精確時間(觸控事件時間回推),不受幀率影響
double pressTime = now - t.pressAge;
switch (Grid.NoteTypeAt(t.x, t.y))
{
case NoteType.Tap:
if (t.began) ProcessTap(t.x, t.y, pressTime);
break;
case NoteType.Hold:
if (t.began) StartHold(t, pressTime, now);
break;
case NoteType.Slide:
// 不提早判定:到達判定點後手指在格子上即算接到(可延遲到判定窗結束)
if (now >= Grid.HitTime(t.x, t.y))
{
Grid.Flash(t.x, t.y, CellFlash.Blue);
Grid.ClearNote(t.x, t.y);
AddScore(Judgement.Perfect, SlideScore);
}
break;
}
}
if (clip != null)
{
progress.anchorMax = new Vector2(Mathf.Clamp01((float)(now / clip.length)), 1);
// 歌曲(含結尾緩衝)結束
if (now > clip.length + NoteJudge.BadWindow + 0.5) App.StartCoroutine(Finish());
}
}
public override void LateTick()
{
if (state == State.Playing) chart.Tick(Grid, SongClock.Now);
}
// 只做判定,不給分、不清除(None = 不在判定範圍)
Judgement JudgeHead(int x, int y, double pressTime)
{
Judgement j = NoteJudge.Evaluate(pressTime - Grid.HitTime(x, y));
return j == Judgement.Miss ? Judgement.None : j;
}
void ProcessTap(int x, int y, double pressTime)
{
Judgement j = JudgeHead(x, y, pressTime);
if (j == Judgement.None) return;
Grid.Flash(x, y, FlashFor(j));
AddScore(j, NoteJudge.Score(j));
Grid.ClearNote(x, y);
}
void StartHold(GridTouch t, double pressTime, double now)
{
int holdMs = Grid.HoldMs(t.x, t.y);
double hit = Grid.HitTime(t.x, t.y);
Judgement j = JudgeHead(t.x, t.y, pressTime);
if (j == Judgement.None || holdMs <= 0) return;
// Hold 頭判先記住,按滿才給分
Grid.Flash(t.x, t.y, FlashFor(j));
Grid.ClearNote(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);
Grid.StartRing(t.x, t.y, (float)(hit + h.duration - now));
}
void FinishHold(ActiveHold h, double now)
{
if (now >= h.hitTime + h.duration - 0.02)
{
// 按滿:頭判分數 + 持續段分數
Grid.Flash(h.x, h.y, CellFlash.Blue);
AddScore(h.head, NoteJudge.Score(h.head) + HoldFullScore);
}
else
{
// 提早放開:亮紅色、不給分
Grid.Flash(h.x, h.y, CellFlash.Red);
AddScore(Judgement.Miss, 0);
}
Grid.StopRing(h.x, h.y);
holds.Remove(h);
}
void OnExpired(int x, int y, NoteType type)
{
if (state != State.Playing) return;
Grid.Flash(x, y, CellFlash.Red);
AddScore(Judgement.Miss, 0);
}
void AddScore(Judgement j, int amount)
{
result.Add(j, amount);
scoreText.text = result.score.ToString();
comboText.text = result.combo >= 5 ? $"{result.combo} COMBO" : "";
}
public static CellFlash FlashFor(Judgement j) => j switch
{
Judgement.Perfect => CellFlash.Blue,
Judgement.Fast => CellFlash.Green,
Judgement.Slow => CellFlash.Orange,
_ => CellFlash.Red,
};
// ---------- 暫停 ----------
public void OnAppPause()
{
if (state == State.Playing) Pause();
}
void Pause()
{
if (state != State.Playing) return;
state = State.Paused;
SongClock.Pause();
App.Music.Pause();
if (video != null && video.isPlaying) video.Pause();
// 按住中的 Hold 以目前進度結算(放開的手指在暫停期間收不到)
for (int i = holds.Count - 1; i >= 0; i--) FinishHold(holds[i], SongClock.Now);
pauseDialog = new Dialog(App.Overlay, "暫停");
pauseDialog.cancellable = false;
pauseDialog.AddClose("離開", () => Quit());
pauseDialog.AddClose("重來", () => App.Go(new PlayPage(song, level)));
pauseDialog.AddClose("繼續", Resume, primary: true);
}
void Resume()
{
// 倒回一點再接續,讓玩家有時間準備
double resumeAt = SongClock.PausedAt - ResumeRewind;
var music = App.Music;
double dsp = AudioSettings.dspTime + 0.1;
if (resumeAt >= 0)
{
music.time = (float)resumeAt;
music.PlayScheduled(dsp);
SongClock.Resume(resumeAt, dsp);
}
else
{
music.time = 0;
music.PlayScheduled(dsp - resumeAt);
SongClock.Resume(0, dsp - resumeAt);
}
// 影片在 Tick 裡對齊目前時間後重新播放
if (video != null && video.isPlaying) video.Pause();
videoStarted = false;
App.Input.IgnoreCurrentTouches();
state = State.Playing;
}
public override void Back()
{
if (state == State.Playing) Pause();
else if (state == State.Finished && overlay != null) Quit();
else if (state == State.Loading) Quit();
}
void Quit()
{
state = State.Finished;
App.Go(new ChoosePage());
}
// ---------- 結算 ----------
IEnumerator Finish()
{
state = State.Finished;
pauseButton.gameObject.SetActive(false);
PlayResult.Last = result;
Debug.Log($"[Play] song={song.id} level={level} notes={chart.Count} {result}");
string status;
if (!Prefs.LoggedIn) status = "未登入,成績不會上傳";
else
{
Api.Response r = null;
// 曲包不在伺服器上註冊過時,伺服器會用這些資訊建立歌曲資料
yield return Api.Game(new Dictionary<string, object>
{
["request"] = "user_play",
["uid"] = Prefs.UserId,
["token"] = PlayerPrefs.GetString(Prefs.Token, ""),
["song"] = song.id,
["title"] = song.name,
["artist"] = song.artist,
["bpm"] = song.bpm,
["duration_sec"] = Mathf.RoundToInt(clip.length),
["level"] = level,
["level_num"] = song.levelNum[level],
["score"] = result.score,
}, x => r = x);
status = r.error == null ? "成績已上傳" : "成績上傳失敗:" + r.error;
}
if (App.Current != this) yield break;
scoreText.gameObject.SetActive(false);
comboText.gameObject.SetActive(false);
overlay = ResultOverlay.Show(result, chart.Count, Ui.Font, status);
// 等待一次新的點擊(忽略結算出現前就按著的手指)
yield return new WaitForSecondsRealtime(0.6f);
while (App.Current == this && !GridInput.AnyNewTap()) yield return null;
if (App.Current == this) Quit();
}
public override void Exit()
{
state = State.Finished;
Grid.NoteExpired -= OnExpired;
Library.Paused = false;
SongClock.Stop();
App.Music.Stop();
if (App.Music.clip == clip) App.Music.clip = null;
if (clip != null) UnityEngine.Object.Destroy(clip);
if (video != null) UnityEngine.Object.Destroy(video.gameObject);
if (videoTexture != null)
{
App.Background.texture = null;
videoTexture.Release();
UnityEngine.Object.Destroy(videoTexture);
}
if (overlay != null) UnityEngine.Object.Destroy(overlay);
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3e2f63f884d58af43bafffd2c824e590
+202
View File
@@ -0,0 +1,202 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using UnityEngine.UI;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
// 設定:延遲校正、曲包資料夾位置、背景影片
// 延遲校正:播放節拍聲,玩家只聽聲音跟著點擊;取偏差中位數存成 AudioOffsetMs
public class SettingsPage : Page, ILibraryListener
{
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;
public override bool UsesGrid => false;
private Text offsetText, statusText, beatText, storageText;
private Button startButton, accessButton, videoButton;
private AudioClip clickTrack;
private bool running, hadAccess;
private readonly List<double> deltas = new List<double>();
private readonly HashSet<int> ignoredTouches = new HashSet<int>();
public override void Enter()
{
App.Music.Stop();
SongClock.Stop();
var back = Ui.Button(Top, "返回", () => App.Go(new MainPage()), 40);
Ui.Place((RectTransform)back.transform, new Vector2(0, 1), new Vector2(40, -30), new Vector2(200, 100));
var title = Ui.Label(Top, "設定", 64, Color.white);
Ui.Place(title.rectTransform, new Vector2(0.5f, 1), new Vector2(0, -30), new Vector2(600, 100));
var holder = Ui.Stretch(Ui.Rect(Top, "Body"), 40, 0, 40, 160);
var col = Ui.Scroll(holder, 26, 10);
Section(col, "延遲校正");
Ui.Label(col, "戴上平常玩的耳機,按「開始」後只聽聲音、跟著節拍點擊螢幕任意處\n前 4 拍為暖身不計分", 36, Ui.Muted);
offsetText = Ui.Label(col, "", 52, Ui.Accent);
beatText = Ui.Height(Ui.Label(col, "", 96, Color.white), 120);
statusText = Ui.Label(col, "", 36, Ui.Muted);
startButton = Ui.Height(Ui.Button(col, "開始", StartCalibration, 48, primary: true), 120);
var row = Ui.Height(Ui.Row(col), 110);
Ui.Button(row, "-5 ms", () => SetOffset(Offset - 5), 40);
Ui.Button(row, "重設", () => SetOffset(0), 40);
Ui.Button(row, "+5 ms", () => SetOffset(Offset + 5), 40);
Ui.Label(col, "正值 = 聲音比畫面晚(藍牙耳機通常為正)", 32, Ui.Muted);
Section(col, "曲包資料夾");
storageText = Ui.Label(col, "", 36, Ui.Muted);
accessButton = Ui.Height(Ui.Button(col, "允許「所有檔案存取權」", PackStorage.RequestSharedAccess, 42), 110);
Ui.Height(Ui.Button(col, "重新掃描", Library.Rescan, 42), 110);
Section(col, "畫面");
videoButton = Ui.Height(Ui.Button(col, "", ToggleVideo, 42), 110);
Ui.Label(col, $"\nRhyculator Alpha {Application.version}", 30, Ui.Muted);
EnhancedTouchSupport.Enable();
clickTrack = BuildClickTrack();
hadAccess = PackStorage.HasSharedAccess();
RefreshOffset();
LibraryChanged();
RefreshVideo();
}
static void Section(Transform parent, string name)
{
var t = Ui.Label(parent, name, 48, Color.white, TextAnchor.MiddleLeft);
t.fontStyle = FontStyle.Bold;
Ui.Height(t, 90);
}
public void LibraryChanged()
{
bool shared = PackStorage.HasSharedAccess();
string where = ChoosePage.DisplayPath(PackStorage.PackageDir);
storageText.text = $"<color=#FF66C4>{where}</color>\n目前 {Library.Songs.Count} 個曲包 · " +
(shared ? "已允許所有檔案存取權" : PackStorage.SupportsShared ? "未授權:曲包放在 app 自己的資料夾" : "");
accessButton.gameObject.SetActive(PackStorage.SupportsShared && !shared);
}
// ---------- 背景影片 ----------
void ToggleVideo()
{
Prefs.SetBool(Prefs.VideoBackground, !Prefs.GetBool(Prefs.VideoBackground, true));
RefreshVideo();
}
void RefreshVideo() => Ui.SetButtonText(videoButton, "曲包背景影片:" + (Prefs.GetBool(Prefs.VideoBackground, true) ? "開" : "關"));
// ---------- 延遲校正 ----------
static int Offset => PlayerPrefs.GetInt(Prefs.AudioOffsetMs, 0);
public override void Tick(List<GridTouch> touches)
{
// 從系統授權畫面回來:位置改變
bool access = PackStorage.HasSharedAccess();
if (access != hadAccess)
{
hadAccess = access;
Library.Rescan();
LibraryChanged();
}
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}";
double real = Time.realtimeSinceStartupAsDouble;
foreach (var t in Touch.activeTouches)
{
if (t.phase != UnityEngine.InputSystem.TouchPhase.Began || 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);
}
if (now > LeadIn + (BeatCount - 0.5) * Interval + 0.3) Finish();
}
void StartCalibration()
{
deltas.Clear();
ignoredTouches.Clear();
// 開始前已按著的手指(按下「開始」的那一下)不計入
foreach (var t in Touch.activeTouches) ignoredTouches.Add(t.touchId);
double dspStart = AudioSettings.dspTime + 0.2;
App.Music.clip = clickTrack;
App.Music.loop = false;
App.Music.PlayScheduled(dspStart);
SongClock.Begin(dspStart, applyOffset: false);
running = true;
startButton.interactable = false;
statusText.text = "閉上眼睛,跟著聲音點擊螢幕任意處";
}
void Finish()
{
running = false;
SongClock.Stop();
App.Music.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(Prefs.AudioOffsetMs, Mathf.Clamp(ms, -500, 500));
PlayerPrefs.Save();
RefreshOffset();
}
void RefreshOffset() => offsetText.text = $"目前延遲補償:{Offset:+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;
}
public override void Exit()
{
if (running) SongClock.Stop();
App.Music.Stop();
if (App.Music.clip == clickTrack) App.Music.clip = null;
if (clickTrack != null) Object.Destroy(clickTrack);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f3c820e04a29bb48b04cf0685fdf378
+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
+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
+24
View File
@@ -0,0 +1,24 @@
using UnityEngine;
using UnityEngine.UI;
// 螢幕某點是否被 UI(按鈕、輸入框、對話框)擋住
// 格子與一般圖片、文字都不是 raycastTarget,所以只要有 raycastTarget 的圖形就算擋住
public static class UIHitTest
{
public static bool IsBlocked(Vector2 screenPos)
{
foreach (var canvas in Object.FindObjectsByType<Canvas>(FindObjectsSortMode.None))
{
if (!canvas.isActiveAndEnabled) continue;
Camera cam = canvas.rootCanvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.rootCanvas.worldCamera;
var graphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(canvas);
for (int i = 0; i < graphics.Count; i++)
{
Graphic g = graphics[i];
if (!g.isActiveAndEnabled || g.depth < 0 || g.canvasRenderer.cull) continue;
if (RectTransformUtility.RectangleContainsScreenPoint(g.rectTransform, screenPos, cam)) return true;
}
}
return false;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3b514edd2240c764db075f214a207d42
+299
View File
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
// 以程式建立 UI 的小工具(遊戲沒有預先擺好的場景與 prefab)
// 單位:畫布寬固定 1080
public static class Ui
{
public static readonly Color Bg = Color.black;
public static readonly Color Panel = new Color(0.09f, 0.09f, 0.11f);
public static readonly Color ButtonFill = new Color(0.16f, 0.16f, 0.19f);
public static readonly Color Line = new Color(0.33f, 0.33f, 0.36f);
public static readonly Color TextColor = new Color(0.93f, 0.93f, 0.95f);
public static readonly Color Muted = new Color(0.6f, 0.6f, 0.64f);
public static readonly Color Accent = new Color(1f, 0.4f, 0.77f);
public static readonly Color Blue = new Color(0.25f, 0.64f, 1f);
public static readonly Color Danger = new Color(1f, 0.38f, 0.38f);
// 難度顏色:[0] 未用、easy、normal、hard
public static readonly Color[] LevelColors =
{
Color.white, new Color(0.49f, 0.84f, 0.49f), new Color(1f, 0.31f, 0.31f), new Color(0.71f, 0.39f, 1f),
};
private static Font font;
public static Font Font => font != null ? font : (font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"));
private static Sprite rounded;
// 圓角矩形(9-slice),按鈕、輸入框、對話框共用
public static Sprite Rounded
{
get
{
if (rounded != null) return rounded;
const int size = 64, r = 20;
var tex = new Texture2D(size, size, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp };
var px = new Color32[size * size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
{
float dx = Mathf.Max(0, Mathf.Max(r - x - 0.5f, x + 0.5f - (size - r)));
float dy = Mathf.Max(0, Mathf.Max(r - y - 0.5f, y + 0.5f - (size - r)));
float a = Mathf.Clamp01(r - Mathf.Sqrt(dx * dx + dy * dy) + 0.5f);
px[y * size + x] = new Color32(255, 255, 255, (byte)(a * 255));
}
tex.SetPixels32(px);
tex.Apply(false, true);
rounded = Sprite.Create(tex, new Rect(0, 0, size, size), new Vector2(0.5f, 0.5f), 100, 0,
SpriteMeshType.FullRect, new Vector4(r, r, r, r));
return rounded;
}
}
// ---------- 基本元件 ----------
public static RectTransform Rect(Transform parent, string name = "Rect")
{
var go = new GameObject(name, typeof(RectTransform));
go.transform.SetParent(parent, false);
return (RectTransform)go.transform;
}
public static RectTransform Stretch(RectTransform rt, float left = 0, float bottom = 0, float right = 0, float top = 0)
{
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.one;
rt.offsetMin = new Vector2(left, bottom);
rt.offsetMax = new Vector2(-right, -top);
return rt;
}
// 以錨點(0~1)放置:pivot 與錨點相同,pos 為偏移
public static RectTransform Place(RectTransform rt, Vector2 anchor, Vector2 pos, Vector2 size)
{
rt.anchorMin = rt.anchorMax = rt.pivot = anchor;
rt.anchoredPosition = pos;
rt.sizeDelta = size;
return rt;
}
public static Text Label(Transform parent, string text, int size, Color color, TextAnchor align = TextAnchor.MiddleCenter)
{
var t = Rect(parent, "Text").gameObject.AddComponent<Text>();
t.font = Font;
t.text = text;
t.fontSize = size;
t.color = color;
t.alignment = align;
t.horizontalOverflow = HorizontalWrapMode.Wrap;
t.verticalOverflow = VerticalWrapMode.Overflow;
t.raycastTarget = false;
t.supportRichText = true;
return t;
}
public static Image Image(Transform parent, Sprite sprite, Color color)
{
var img = Rect(parent, "Image").gameObject.AddComponent<Image>();
img.sprite = sprite;
img.color = color;
img.raycastTarget = false;
if (sprite == Rounded) img.type = UnityEngine.UI.Image.Type.Sliced;
return img;
}
public static Button Button(Transform parent, string label, UnityAction onClick, int fontSize = 44, bool primary = false)
{
var img = Image(parent, Rounded, primary ? new Color(0.45f, 0.17f, 0.34f) : ButtonFill);
img.raycastTarget = true;
img.name = "Button";
var btn = img.gameObject.AddComponent<Button>();
var colors = btn.colors;
colors.highlightedColor = Color.white;
colors.pressedColor = new Color(0.7f, 0.7f, 0.7f);
colors.disabledColor = new Color(0.5f, 0.5f, 0.5f, 0.6f);
btn.colors = colors;
if (onClick != null) btn.onClick.AddListener(onClick);
var outline = Image(img.transform, Rounded, primary ? Accent : Line);
outline.fillCenter = false;
Stretch(outline.rectTransform);
var t = Label(img.transform, label, fontSize, TextColor);
Stretch(t.rectTransform, 16, 4, 16, 4);
return btn;
}
public static void SetButtonText(Button b, string text) => b.GetComponentInChildren<Text>().text = text;
public static InputField Input(Transform parent, string placeholder, InputField.ContentType type = InputField.ContentType.Standard, int fontSize = 42)
{
var bg = Image(parent, Rounded, new Color(0.05f, 0.05f, 0.06f));
bg.raycastTarget = true;
bg.name = "Input";
var outline = Image(bg.transform, Rounded, Line);
outline.fillCenter = false;
Stretch(outline.rectTransform);
var text = Label(bg.transform, "", fontSize, TextColor, TextAnchor.MiddleLeft);
text.supportRichText = false;
text.horizontalOverflow = HorizontalWrapMode.Overflow;
Stretch(text.rectTransform, 28, 4, 28, 4);
var ph = Label(bg.transform, placeholder, fontSize, new Color(0.45f, 0.45f, 0.5f), TextAnchor.MiddleLeft);
Stretch(ph.rectTransform, 28, 4, 28, 4);
var field = bg.gameObject.AddComponent<InputField>();
field.textComponent = text;
field.placeholder = ph;
field.contentType = type;
field.lineType = InputField.LineType.SingleLine;
field.caretColor = Accent;
field.selectionColor = new Color(1f, 0.4f, 0.77f, 0.35f);
field.caretWidth = 3;
return field;
}
// 垂直排列容器(表單、清單用):子物件以 LayoutElement 指定高度
public static RectTransform Column(Transform parent, float spacing = 24, int padding = 0, TextAnchor align = TextAnchor.UpperCenter)
{
var rt = Rect(parent, "Column");
var v = rt.gameObject.AddComponent<VerticalLayoutGroup>();
v.spacing = spacing;
v.padding = new RectOffset(padding, padding, padding, padding);
v.childAlignment = align;
v.childControlWidth = v.childControlHeight = true;
v.childForceExpandWidth = true;
v.childForceExpandHeight = false;
return rt;
}
public static RectTransform Row(Transform parent, float spacing = 24)
{
var rt = Rect(parent, "Row");
var h = rt.gameObject.AddComponent<HorizontalLayoutGroup>();
h.spacing = spacing;
h.childAlignment = TextAnchor.MiddleCenter;
h.childControlWidth = h.childControlHeight = true;
h.childForceExpandWidth = true;
h.childForceExpandHeight = true;
return rt;
}
public static T Height<T>(T c, float height) where T : Component
{
var le = c.GetComponent<LayoutElement>() ?? c.gameObject.AddComponent<LayoutElement>();
le.minHeight = le.preferredHeight = height;
return c;
}
// 可捲動的內容區(放在 parent 內填滿);回傳要放內容的 Column
public static RectTransform Scroll(Transform parent, float spacing = 24, int padding = 24)
{
var view = Image(parent, null, new Color(0, 0, 0, 0));
view.raycastTarget = true; // 讓拖曳可以捲動
view.name = "Scroll";
Stretch(view.rectTransform);
view.gameObject.AddComponent<RectMask2D>();
var scroll = view.gameObject.AddComponent<ScrollRect>();
scroll.horizontal = false;
scroll.movementType = ScrollRect.MovementType.Clamped;
scroll.scrollSensitivity = 40;
var content = Column(view.transform, spacing, padding);
content.anchorMin = new Vector2(0, 1);
content.anchorMax = new Vector2(1, 1);
content.pivot = new Vector2(0.5f, 1);
content.offsetMin = content.offsetMax = Vector2.zero;
content.gameObject.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
scroll.viewport = view.rectTransform;
scroll.content = content;
return content;
}
}
// 對話框:半透明遮罩 + 置中面板(標題、內文、自訂內容、按鈕列)
// 開著時格子不接受觸控;返回鍵關閉最上層(cancellable 時)
public class Dialog
{
private static readonly List<Dialog> open = new List<Dialog>();
public static bool AnyOpen => open.Count > 0;
public readonly RectTransform root;
public readonly RectTransform body; // 面板內的 Column,可加入自訂內容
public readonly Text message;
public bool cancellable = true;
public event Action Closed;
private RectTransform buttons;
public Dialog(Transform layer, string title, string text = null)
{
var dim = Ui.Image(layer, null, new Color(0, 0, 0, 0.75f));
dim.raycastTarget = true;
dim.name = "Dialog";
root = Ui.Stretch(dim.rectTransform);
var panel = Ui.Image(root, Ui.Rounded, Ui.Panel);
panel.raycastTarget = true;
var prt = panel.rectTransform;
prt.anchorMin = prt.anchorMax = prt.pivot = new Vector2(0.5f, 0.5f);
prt.sizeDelta = new Vector2(940, 0);
var outline = Ui.Image(prt, Ui.Rounded, Ui.Line);
outline.fillCenter = false;
Ui.Stretch(outline.rectTransform);
outline.gameObject.AddComponent<LayoutElement>().ignoreLayout = true;
body = Ui.Column(prt, 28, 48);
var fitter = panel.gameObject.AddComponent<ContentSizeFitter>();
fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
// 面板高度跟著內容:讓 Column 的偏好高度傳到面板
var v = panel.gameObject.AddComponent<VerticalLayoutGroup>();
v.childControlHeight = v.childControlWidth = true;
v.childForceExpandHeight = false;
if (!string.IsNullOrEmpty(title))
Ui.Label(body, title, 56, Ui.TextColor).fontStyle = FontStyle.Bold;
message = Ui.Label(body, text ?? "", 40, Ui.Muted);
message.gameObject.SetActive(!string.IsNullOrEmpty(text));
open.Add(this);
}
public Button AddButton(string label, Action onClick, bool primary = false)
{
if (buttons == null)
{
buttons = Ui.Row(body, 24);
Ui.Height(buttons, 120);
}
var b = Ui.Button(buttons, label, () => onClick?.Invoke(), 44, primary);
return b;
}
// 按鈕:關閉對話框後執行
public Button AddClose(string label, Action then = null, bool primary = false)
=> AddButton(label, () => { Close(); then?.Invoke(); }, primary);
public bool IsOpen => root != null;
public void Close()
{
if (root == null) return;
open.Remove(this);
UnityEngine.Object.Destroy(root.gameObject);
Closed?.Invoke();
}
// 返回鍵:關閉最上層可取消的對話框;有關閉任何對話框時回傳 true
public static bool HandleBack()
{
if (open.Count == 0) return false;
var top = open[open.Count - 1];
if (top.cancellable) top.Close();
return true;
}
public static void CloseAll()
{
for (int i = open.Count - 1; i >= 0; i--) open[i].Close();
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 47e9856f5baa7894fa4a8a1039940881