Files
Convention-Unity-Demo/Assets/Scripts/Framework/RootObject.cs

109 lines
3.5 KiB
C#
Raw Normal View History

2025-09-25 19:04:05 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using Convention;
using Convention.VFX;
using Convention.WindowsUI.Variant;
using Demo.Editor.UI;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Demo.Game
{
public class RootObject : ScriptableObject
{
[Resources] public BasicAudioSystem audioSystem;
[Content] public GameController RootGameController;
public override IEnumerator LoadScript(string script)
{
try
{
yield return base.LoadScript(script);
}
finally
{
ScriptUpdate(RootGameController.SongOffset, 0.01f, TickType.Start);
2025-09-25 19:04:05 +08:00
if (RootGameController.IsMain)
{
Keyboard.current.onTextInput += InputCatchChar;
}
}
}
public override IEnumerator UnloadScript()
{
if (RootGameController.IsMain)
{
Keyboard.current.onTextInput -= InputCatchChar;
}
yield return base.UnloadScript();
}
public void EnableScript(string sourcePath, string scriptPath, GameController parent)
{
base.EnableScript(sourcePath, scriptPath, nameof(RootObject), null);
RootGameController = parent;
}
[Serializable]
public struct InputCatchEntry
{
public float TimePoint;
public Vector2 Position;
public string InputKey;
}
/// <summary>
/// 这个捕获列表大多数时候只构造一次,等同与<see langword="readonly"/>
/// 但是会在<see cref="SubWorld"/>中被父关卡加载后会被赋值,这是唯一的例外,
/// 在多World项目中会由父世界的<see cref="SubWorld"/>传递给其他加载进来的<see cref="RootObject"/>
/// </summary>
public List<InputCatchEntry> InputCatch = new();
private void InputCatchChar(char ch)
{
if (RootGameController.IsAutoPlay)
return;
if (RootGameController.MainAudio.IsPlaying() == false)
return;
InputCatch.Add(new()
{
TimePoint = CurrentUpdateTickTimePoint,
InputKey = ch.ToString(),
Position = Mouse.current.position.ReadValue()
});
}
private float CurrentUpdateTickTimePoint;
protected override void UpdateTicks(float currentTime, float deltaTime, TickType tickType)
{
if (RootGameController.IsMain)
{
void Foo()
{
if (RootGameController.IsAutoPlay)
return;
if (RootGameController.MainAudio.IsPlaying() == false)
return;
// 更新缓存时间
CurrentUpdateTickTimePoint = currentTime;
// 将距离当前更近的输入调整到更靠前的位置
InputCatch.Sort((x, y) => Mathf.Abs(x.TimePoint - currentTime).CompareTo(y.TimePoint - currentTime));
if (InputCatch.Count > 50)
InputCatch = InputCatch.GetRange(0, 50);
if (tickType == TickType.Start)
{
InputCatch.Clear();
}
}
Foo();
}
base.UpdateTicks(currentTime, deltaTime, tickType);
}
}
}