Add main menu scene with Rive UI, procedural background, and scene transitions
- Add Menu scene with Rive-driven login and navigation UI (RiveLoginController, RiveNavigationController) for entering a username and starting/navigating the client via Rive triggers - Add SceneTransitionController to fade out and load the Landscape gameplay scene when Play is selected - Add procedural low-poly triangle field background and animated wave panel (LowPolyTriangleField, TriangleWavePanel) with matching editor menus and materials - Add MenuLightAnimator for animated menu lighting and UI fade helpers (MenuFadeIn, DebugFadeToggle/Bridge) - Rename SampleScene to Landscape and wire ChatNetworkManager to hide the new Rive login canvas once gameplay starts - Bump Input System action codegen version and add Rive package references/project settings updates to support the new UI
This commit is contained in:
@@ -6,6 +6,7 @@ using System.Collections.Generic;
|
||||
public class ChatNetworkManager : NetworkManager
|
||||
{
|
||||
[SerializeField] private GameObject chatUIPrefab;
|
||||
[SerializeField] private GameObject riveLoginCanvas;
|
||||
|
||||
// Server-side authoritative store of chat messages
|
||||
private readonly List<string> chatMessages = new();
|
||||
@@ -61,6 +62,11 @@ public class ChatNetworkManager : NetworkManager
|
||||
return;
|
||||
}
|
||||
|
||||
if (riveLoginCanvas == null)
|
||||
{
|
||||
Debug.LogError("ChatNetworkManager: Rive Login Canvas is not assigned in the inspector!");
|
||||
}
|
||||
|
||||
// Check if ChatUI already exists to avoid duplicates
|
||||
ChatUI existingChatUI = FindFirstObjectByType<ChatUI>();
|
||||
if (existingChatUI == null)
|
||||
@@ -80,6 +86,9 @@ public class ChatNetworkManager : NetworkManager
|
||||
{
|
||||
LoginUI.instance.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
if (riveLoginCanvas != null)
|
||||
riveLoginCanvas.SetActive(false);
|
||||
}
|
||||
|
||||
[Server]
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c71d54b8abd9a114ca51f94932b0e47f
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.IO;
|
||||
using Procedural;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
|
||||
namespace ProceduralEditor
|
||||
{
|
||||
public static class LowPolyTriangleFieldMenu
|
||||
{
|
||||
const string MaterialsFolder = "Assets/Materials";
|
||||
const string FaceMaterialPath = MaterialsFolder + "/LowPolyTriangleFace.mat";
|
||||
const string EdgeMaterialPath = MaterialsFolder + "/LowPolyTriangleEdge.mat";
|
||||
|
||||
[MenuItem("Tools/Scene/Add Low Poly Triangle Field")]
|
||||
public static void CreateInScene()
|
||||
{
|
||||
var faceMaterial = GetOrCreateMaterial(FaceMaterialPath, "Universal Render Pipeline/Lit", mat =>
|
||||
{
|
||||
mat.SetColor("_BaseColor", new Color(0.09f, 0.11f, 0.14f));
|
||||
if (mat.HasProperty("_Smoothness")) mat.SetFloat("_Smoothness", 0.45f);
|
||||
if (mat.HasProperty("_Metallic")) mat.SetFloat("_Metallic", 0.05f);
|
||||
if (mat.HasProperty("_Cull")) mat.SetFloat("_Cull", 0f);
|
||||
});
|
||||
|
||||
var edgeMaterial = GetOrCreateMaterial(EdgeMaterialPath, "Universal Render Pipeline/Unlit", mat =>
|
||||
{
|
||||
mat.SetColor("_BaseColor", Color.white);
|
||||
if (mat.HasProperty("_Cull")) mat.SetFloat("_Cull", 0f);
|
||||
});
|
||||
|
||||
var go = new GameObject("Low Poly Triangle Field");
|
||||
Undo.RegisterCreatedObjectUndo(go, "Add Low Poly Triangle Field");
|
||||
go.transform.position = new Vector3(0f, -1.5f, 15f);
|
||||
go.transform.rotation = Quaternion.identity;
|
||||
|
||||
var field = go.AddComponent<LowPolyTriangleField>();
|
||||
field.faceMaterial = faceMaterial;
|
||||
field.edgeMaterial = edgeMaterial;
|
||||
|
||||
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
|
||||
Selection.activeGameObject = go;
|
||||
if (SceneView.lastActiveSceneView != null)
|
||||
SceneView.lastActiveSceneView.FrameSelected();
|
||||
}
|
||||
|
||||
static Material GetOrCreateMaterial(string path, string shaderName, System.Action<Material> configure)
|
||||
{
|
||||
var existing = AssetDatabase.LoadAssetAtPath<Material>(path);
|
||||
if (existing != null) return existing;
|
||||
|
||||
if (!AssetDatabase.IsValidFolder(MaterialsFolder))
|
||||
AssetDatabase.CreateFolder("Assets", "Materials");
|
||||
|
||||
var shader = Shader.Find(shaderName);
|
||||
if (shader == null)
|
||||
{
|
||||
Debug.LogError($"LowPolyTriangleFieldMenu: could not find shader '{shaderName}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var mat = new Material(shader);
|
||||
configure(mat);
|
||||
AssetDatabase.CreateAsset(mat, path);
|
||||
AssetDatabase.SaveAssets();
|
||||
return mat;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc73da416d6f5454b90b1954130688d9
|
||||
@@ -0,0 +1,340 @@
|
||||
using Procedural;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace ProceduralEditor
|
||||
{
|
||||
public static class SetupMainMenuScene
|
||||
{
|
||||
const string ScenePath = "Assets/Scenes/Menu.unity";
|
||||
const string MaterialsFolder = "Assets/Materials";
|
||||
const string FaceMaterialPath = MaterialsFolder + "/LowPolyTriangleFace.mat";
|
||||
const string SettingsFolder = "Assets/Settings";
|
||||
const string PostProcessProfilePath = SettingsFolder + "/MenuPostProcessProfile.asset";
|
||||
|
||||
// Slightly deeper background and a wider field of view for a more open framing
|
||||
static readonly Color BackgroundColor = new Color(0.92f, 0.93f, 0.95f);
|
||||
static readonly Vector3 PanelCenter = new Vector3(0f, 0f, 10f);
|
||||
|
||||
[MenuItem("Tools/Scene/Setup Main Menu Scene")]
|
||||
public static void Setup()
|
||||
{
|
||||
if (EditorApplication.isPlaying)
|
||||
{
|
||||
Debug.LogError("Setup Main Menu Scene: exit Play Mode first — EditorSceneManager.OpenScene() can't run during Play Mode.");
|
||||
return;
|
||||
}
|
||||
|
||||
var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
|
||||
|
||||
var faceMaterial = GetOrCreateMaterial(FaceMaterialPath, "Universal Render Pipeline/Lit", mat =>
|
||||
{
|
||||
mat.SetColor("_BaseColor", new Color(0.08f, 0.09f, 0.12f));
|
||||
if (mat.HasProperty("_Smoothness")) mat.SetFloat("_Smoothness", 0.3f);
|
||||
if (mat.HasProperty("_Metallic")) mat.SetFloat("_Metallic", 0.05f);
|
||||
if (mat.HasProperty("_Cull")) mat.SetFloat("_Cull", 0f);
|
||||
});
|
||||
|
||||
SetupQuality();
|
||||
SetupCamera();
|
||||
SetupLight();
|
||||
SetupPanel(faceMaterial);
|
||||
SetupFog();
|
||||
SetupPostProcessVolume();
|
||||
SetupFadeCanvas();
|
||||
|
||||
EditorSceneManager.MarkSceneDirty(scene);
|
||||
Debug.Log("Main Menu scene set up. Review the Game view framing, then save the scene.");
|
||||
}
|
||||
|
||||
static void SetupCamera()
|
||||
{
|
||||
var cam = Camera.main;
|
||||
if (cam == null)
|
||||
{
|
||||
var go = new GameObject("Main Camera", typeof(Camera), typeof(AudioListener));
|
||||
go.tag = "MainCamera";
|
||||
cam = go.GetComponent<Camera>();
|
||||
}
|
||||
|
||||
// Position/rotation/FOV captured from the live scene after manual framing in the
|
||||
// Editor (approved there first, then copied back here) rather than computed — the
|
||||
// rotation includes a deliberate manual roll (Z) that a LookAt-based rotation
|
||||
// wouldn't produce, and the narrow FOV is a much tighter, more telephoto framing
|
||||
// than the original 60.
|
||||
cam.transform.position = new Vector3(-0.86f, 0.07f, 5.88f);
|
||||
cam.transform.rotation = Quaternion.Euler(-29.064f, -21.054f, -11.311f);
|
||||
// Increased FOV to give a more open, less telephoto composition
|
||||
cam.fieldOfView = 35f;
|
||||
cam.clearFlags = CameraClearFlags.SolidColor;
|
||||
cam.backgroundColor = BackgroundColor;
|
||||
cam.nearClipPlane = 0.3f;
|
||||
cam.farClipPlane = 60f;
|
||||
// URP silently disables TAA when MSAA is active (they're mutually exclusive) — the
|
||||
// pipeline asset has MSAA on for other scenes (see SetupQuality), so it's turned off
|
||||
// per-camera here rather than touching that shared, project-wide asset.
|
||||
cam.allowMSAA = false;
|
||||
|
||||
// URP has no "Post Process Layer" component (that's Built-in RP's Post-Processing
|
||||
// Stack v2) — post-processing is a per-camera flag on UniversalAdditionalCameraData
|
||||
// plus the antialiasing mode below; that combination is the URP equivalent.
|
||||
//
|
||||
// Switched from SMAA to TAA (Temporal Anti-Aliasing) for higher quality — SMAA was
|
||||
// already maxed at "High" quality with no further headroom, while TAA accumulates
|
||||
// sub-pixel samples across frames and handles the specular sparkle far better.
|
||||
// Tradeoff: TAA can ghost/smear on continuously moving edges, and this panel never
|
||||
// stops moving (wave + tilt + sway), so varianceClampScale is pulled down from URP's
|
||||
// default (0.9 -> 0.65) to bias toward less ghosting, with contrast-adaptive
|
||||
// sharpening turned on to counter the softening TAA otherwise introduces. Watch for
|
||||
// trailing/streaking behind fast-moving edges — if it shows up, SMAA is the fallback.
|
||||
var camData = cam.GetComponent<UniversalAdditionalCameraData>();
|
||||
if (camData == null) camData = cam.gameObject.AddComponent<UniversalAdditionalCameraData>();
|
||||
camData.renderPostProcessing = true;
|
||||
camData.antialiasing = AntialiasingMode.TemporalAntiAliasing;
|
||||
ref var taa = ref camData.taaSettings;
|
||||
taa.quality = TemporalAAQuality.High;
|
||||
taa.varianceClampScale = 0.65f;
|
||||
taa.contrastAdaptiveSharpening = 0.6f;
|
||||
}
|
||||
|
||||
static void SetupLight()
|
||||
{
|
||||
Light light = Object.FindFirstObjectByType<Light>();
|
||||
GameObject go;
|
||||
if (light == null)
|
||||
{
|
||||
go = new GameObject("Directional Light", typeof(Light));
|
||||
light = go.GetComponent<Light>();
|
||||
}
|
||||
else
|
||||
{
|
||||
go = light.gameObject;
|
||||
}
|
||||
|
||||
light.type = LightType.Directional;
|
||||
go.transform.position = new Vector3(0f, 3f, 0f);
|
||||
// The panel's visible faces have world normal +Z, so the light needs a strong
|
||||
// -Z travel direction (yaw ~180) to actually illuminate them head-on instead of
|
||||
// grazing the wall edge-on the way the old floor-tuned angle did.
|
||||
go.transform.rotation = Quaternion.Euler(35f, 180f, 0f);
|
||||
light.color = new Color(1f, 0.96f, 0.86f);
|
||||
light.intensity = 1.9f;
|
||||
|
||||
RenderSettings.ambientMode = AmbientMode.Flat;
|
||||
RenderSettings.ambientLight = new Color(0.22f, 0.24f, 0.28f);
|
||||
|
||||
if (go.GetComponent<MenuLightAnimator>() == null)
|
||||
go.AddComponent<MenuLightAnimator>();
|
||||
}
|
||||
|
||||
static void SetupPanel(Material faceMaterial)
|
||||
{
|
||||
var existing = GameObject.Find("Triangle Wave Panel");
|
||||
if (existing != null) Object.DestroyImmediate(existing);
|
||||
|
||||
var go = new GameObject("Triangle Wave Panel");
|
||||
go.transform.position = PanelCenter;
|
||||
// Rotate the panel from its default horizontal (floor, XZ) orientation to vertical
|
||||
// (XY, facing the camera along Z). Local Y (the wave/thickness axis) becomes world Z,
|
||||
// so tiles ripple toward/away from the camera instead of bobbing up/down.
|
||||
go.transform.rotation = Quaternion.Euler(90f, 0f, 0f);
|
||||
|
||||
var panel = go.AddComponent<TriangleWavePanel>();
|
||||
// Slightly larger than the minimum frame-filling size, since the camera now views the
|
||||
// panel off-axis (see SetupCamera) rather than dead-on, which eats into the margin.
|
||||
panel.columns = 46;
|
||||
panel.rows = 30;
|
||||
panel.triangleSize = 1f;
|
||||
// Values below captured from the live scene after manual tweaking in the Inspector
|
||||
// (approved there first, then copied back here).
|
||||
panel.gapScale = 0.973f;
|
||||
panel.cornerRadius = 0f;
|
||||
panel.cornerSegments = 3;
|
||||
panel.thickness = 0.15f;
|
||||
panel.waveAmplitude = 0.45f;
|
||||
panel.waveFrequency = 0.18f;
|
||||
panel.waveSpeed = 0.8f;
|
||||
panel.tiltAmount = 1.4f;
|
||||
panel.swayAmplitude = 10f;
|
||||
panel.swaySpeed = 0.2f;
|
||||
panel.showBacker = false;
|
||||
panel.faceMaterial = faceMaterial;
|
||||
panel.backerMaterial = faceMaterial;
|
||||
|
||||
// AddComponent already triggered one Rebuild() using class defaults before the fields
|
||||
// above were set (see TriangleWavePanel.RebuildNow's doc comment) — force a real one
|
||||
// now that the panel is fully configured.
|
||||
panel.RebuildNow();
|
||||
}
|
||||
|
||||
static void SetupFog()
|
||||
{
|
||||
// A vertical, camera-facing wall has no receding horizon to hide, so fog stays off;
|
||||
// the grid is sized so its edges fall outside the frustum instead.
|
||||
RenderSettings.fog = false;
|
||||
}
|
||||
|
||||
static void SetupFadeCanvas()
|
||||
{
|
||||
var existing = GameObject.Find("Fade Canvas");
|
||||
if (existing != null) Object.DestroyImmediate(existing);
|
||||
|
||||
var canvasGo = new GameObject("Fade Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
|
||||
var canvas = canvasGo.GetComponent<Canvas>();
|
||||
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
|
||||
// Ensure fade canvas draws on top of other UI canvases
|
||||
canvas.overrideSorting = true;
|
||||
canvas.sortingOrder = 1000;
|
||||
var scaler = canvasGo.GetComponent<CanvasScaler>();
|
||||
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
|
||||
scaler.referenceResolution = new Vector2(1920, 1080);
|
||||
|
||||
var imageGo = new GameObject("Fade Image", typeof(Image), typeof(CanvasGroup));
|
||||
imageGo.transform.SetParent(canvasGo.transform, false);
|
||||
var image = imageGo.GetComponent<Image>();
|
||||
image.color = new Color(0.03f, 0.03f, 0.04f, 1f);
|
||||
var rect = image.rectTransform;
|
||||
rect.anchorMin = Vector2.zero;
|
||||
rect.anchorMax = Vector2.one;
|
||||
rect.offsetMin = Vector2.zero;
|
||||
rect.offsetMax = Vector2.zero;
|
||||
|
||||
var fadeIn = imageGo.AddComponent<MenuFadeIn>();
|
||||
fadeIn.delay = 0.3f;
|
||||
fadeIn.duration = 3.5f;
|
||||
// Disable automatic fade-on-start so the debug toggle controls opacity predictably.
|
||||
// If you prefer the automatic fade, remove this line.
|
||||
fadeIn.enabled = false;
|
||||
|
||||
// Make sure the image initially is fully opaque so the menu starts covered by the backdrop
|
||||
var initColor = image.color;
|
||||
initColor.a = 1f;
|
||||
image.color = initColor;
|
||||
|
||||
// DEBUG: add a small top-right button to toggle fade (full opacity <-> transparent)
|
||||
var buttonGo = new GameObject("Debug Toggle Fade Button", typeof(RectTransform), typeof(UnityEngine.UI.Button), typeof(Image));
|
||||
buttonGo.transform.SetParent(canvasGo.transform, false);
|
||||
var btnRect = buttonGo.GetComponent<RectTransform>();
|
||||
// anchor to top-right
|
||||
btnRect.anchorMin = new Vector2(1f, 1f);
|
||||
btnRect.anchorMax = new Vector2(1f, 1f);
|
||||
btnRect.pivot = new Vector2(1f, 1f);
|
||||
btnRect.sizeDelta = new Vector2(140f, 32f);
|
||||
btnRect.anchoredPosition = new Vector2(-10f, -10f);
|
||||
|
||||
var btnImage = buttonGo.GetComponent<Image>();
|
||||
btnImage.color = new Color(0.08f, 0.08f, 0.08f, 0.85f);
|
||||
|
||||
var button = buttonGo.GetComponent<UnityEngine.UI.Button>();
|
||||
var colors = button.colors;
|
||||
colors.normalColor = new Color(0.12f, 0.12f, 0.12f, 0.9f);
|
||||
colors.highlightedColor = new Color(0.18f, 0.18f, 0.18f, 0.95f);
|
||||
colors.pressedColor = new Color(0.06f, 0.06f, 0.06f, 0.9f);
|
||||
button.colors = colors;
|
||||
|
||||
// simple text label (legacy UI Text so no TMP dependency required)
|
||||
var textGo = new GameObject("Text", typeof(RectTransform), typeof(UnityEngine.UI.Text));
|
||||
textGo.transform.SetParent(buttonGo.transform, false);
|
||||
var txt = textGo.GetComponent<UnityEngine.UI.Text>();
|
||||
txt.text = "Toggle Fade";
|
||||
txt.alignment = TextAnchor.MiddleCenter;
|
||||
txt.color = Color.white;
|
||||
txt.fontSize = 14;
|
||||
var txtRect = textGo.GetComponent<RectTransform>();
|
||||
txtRect.anchorMin = Vector2.zero;
|
||||
txtRect.anchorMax = Vector2.one;
|
||||
txtRect.offsetMin = Vector2.zero;
|
||||
txtRect.offsetMax = Vector2.zero;
|
||||
|
||||
// add runtime helper (component created in new file DebugFadeToggle.cs)
|
||||
var debugToggle = buttonGo.AddComponent<ProceduralEditor.DebugFadeToggleBridge>();
|
||||
debugToggle.targetImage = image;
|
||||
debugToggle.duration = fadeIn.duration;
|
||||
}
|
||||
|
||||
static void SetupPostProcessVolume()
|
||||
{
|
||||
var existing = GameObject.Find("Post Process Volume");
|
||||
if (existing != null) Object.DestroyImmediate(existing);
|
||||
|
||||
var profile = AssetDatabase.LoadAssetAtPath<VolumeProfile>(PostProcessProfilePath);
|
||||
if (profile == null)
|
||||
{
|
||||
if (!AssetDatabase.IsValidFolder(SettingsFolder))
|
||||
AssetDatabase.CreateFolder("Assets", "Settings");
|
||||
profile = ScriptableObject.CreateInstance<VolumeProfile>();
|
||||
AssetDatabase.CreateAsset(profile, PostProcessProfilePath);
|
||||
}
|
||||
|
||||
if (!profile.TryGet(out DepthOfField dof))
|
||||
dof = profile.Add<DepthOfField>();
|
||||
|
||||
// "Blur" here is depth-of-field rather than a flat uniform blur: at this close a
|
||||
// camera distance (see SetupCamera, Z=7.5 vs panel at Z=10) the panel's own width
|
||||
// creates a big apparent depth range across the frame purely from perspective, so
|
||||
// gaussianStart/End are tuned to keep roughly the center sharp and let the
|
||||
// corners/edges soften — a graduated blur rather than blurring everything equally.
|
||||
dof.active = true;
|
||||
dof.mode.overrideState = true;
|
||||
dof.mode.value = DepthOfFieldMode.Gaussian;
|
||||
dof.gaussianStart.overrideState = true;
|
||||
dof.gaussianStart.value = 2f;
|
||||
dof.gaussianEnd.overrideState = true;
|
||||
dof.gaussianEnd.value = 9f;
|
||||
dof.gaussianMaxRadius.overrideState = true;
|
||||
dof.gaussianMaxRadius.value = 1f;
|
||||
dof.highQualitySampling.overrideState = true;
|
||||
dof.highQualitySampling.value = true;
|
||||
|
||||
EditorUtility.SetDirty(profile);
|
||||
AssetDatabase.SaveAssets();
|
||||
|
||||
var go = new GameObject("Post Process Volume", typeof(Volume));
|
||||
var volume = go.GetComponent<Volume>();
|
||||
volume.isGlobal = true;
|
||||
volume.priority = 0f;
|
||||
volume.weight = 1f;
|
||||
volume.sharedProfile = profile;
|
||||
}
|
||||
|
||||
static void SetupQuality()
|
||||
{
|
||||
// Sets MSAA on the shared pipeline asset for scenes/cameras that still use SMAA/FXAA
|
||||
// (which do benefit from stacking with MSAA). This menu's own camera now uses TAA
|
||||
// instead, which requires MSAA off, so it opts itself out via cam.allowMSAA in
|
||||
// SetupCamera() rather than leaving this project-wide asset at 1x for everyone.
|
||||
if (GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset urpAsset)
|
||||
{
|
||||
urpAsset.msaaSampleCount = 8;
|
||||
EditorUtility.SetDirty(urpAsset);
|
||||
AssetDatabase.SaveAssets();
|
||||
}
|
||||
}
|
||||
|
||||
static Material GetOrCreateMaterial(string path, string shaderName, System.Action<Material> configure)
|
||||
{
|
||||
var existing = AssetDatabase.LoadAssetAtPath<Material>(path);
|
||||
if (existing != null) return existing;
|
||||
|
||||
if (!AssetDatabase.IsValidFolder(MaterialsFolder))
|
||||
AssetDatabase.CreateFolder("Assets", "Materials");
|
||||
|
||||
var shader = Shader.Find(shaderName);
|
||||
if (shader == null)
|
||||
{
|
||||
Debug.LogError($"SetupMainMenuScene: could not find shader '{shaderName}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var mat = new Material(shader);
|
||||
configure(mat);
|
||||
AssetDatabase.CreateAsset(mat, path);
|
||||
AssetDatabase.SaveAssets();
|
||||
return mat;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8a0dd75945e74554192383a532278657
|
||||
@@ -0,0 +1,68 @@
|
||||
using Procedural;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
|
||||
namespace ProceduralEditor
|
||||
{
|
||||
public static class TriangleWavePanelMenu
|
||||
{
|
||||
const string MaterialsFolder = "Assets/Materials";
|
||||
const string FaceMaterialPath = MaterialsFolder + "/LowPolyTriangleFace.mat";
|
||||
const string BackerMaterialPath = MaterialsFolder + "/LowPolyTriangleBacker.mat";
|
||||
|
||||
[MenuItem("Tools/Scene/Add Triangle Wave Panel (Tiles)")]
|
||||
public static void CreateInScene()
|
||||
{
|
||||
var faceMaterial = GetOrCreateMaterial(FaceMaterialPath, "Universal Render Pipeline/Lit", mat =>
|
||||
{
|
||||
mat.SetColor("_BaseColor", new Color(0.09f, 0.11f, 0.14f));
|
||||
if (mat.HasProperty("_Smoothness")) mat.SetFloat("_Smoothness", 0.45f);
|
||||
if (mat.HasProperty("_Metallic")) mat.SetFloat("_Metallic", 0.05f);
|
||||
if (mat.HasProperty("_Cull")) mat.SetFloat("_Cull", 0f);
|
||||
});
|
||||
|
||||
var backerMaterial = GetOrCreateMaterial(BackerMaterialPath, "Universal Render Pipeline/Unlit", mat =>
|
||||
{
|
||||
mat.SetColor("_BaseColor", new Color(0.95f, 0.96f, 0.98f));
|
||||
if (mat.HasProperty("_Cull")) mat.SetFloat("_Cull", 0f);
|
||||
});
|
||||
|
||||
var go = new GameObject("Triangle Wave Panel");
|
||||
Undo.RegisterCreatedObjectUndo(go, "Add Triangle Wave Panel");
|
||||
go.transform.position = new Vector3(0f, -1.5f, 15f);
|
||||
go.transform.rotation = Quaternion.identity;
|
||||
|
||||
var panel = go.AddComponent<TriangleWavePanel>();
|
||||
panel.faceMaterial = faceMaterial;
|
||||
panel.backerMaterial = backerMaterial;
|
||||
|
||||
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
|
||||
Selection.activeGameObject = go;
|
||||
if (SceneView.lastActiveSceneView != null)
|
||||
SceneView.lastActiveSceneView.FrameSelected();
|
||||
}
|
||||
|
||||
static Material GetOrCreateMaterial(string path, string shaderName, System.Action<Material> configure)
|
||||
{
|
||||
var existing = AssetDatabase.LoadAssetAtPath<Material>(path);
|
||||
if (existing != null) return existing;
|
||||
|
||||
if (!AssetDatabase.IsValidFolder(MaterialsFolder))
|
||||
AssetDatabase.CreateFolder("Assets", "Materials");
|
||||
|
||||
var shader = Shader.Find(shaderName);
|
||||
if (shader == null)
|
||||
{
|
||||
Debug.LogError($"TriangleWavePanelMenu: could not find shader '{shaderName}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var mat = new Material(shader);
|
||||
configure(mat);
|
||||
AssetDatabase.CreateAsset(mat, path);
|
||||
AssetDatabase.SaveAssets();
|
||||
return mat;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0f9fa9004d5bfdd419dff0264ed8b171
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8271356abbd97f64c843e4ce0fe4d3bb
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,74 @@
|
||||
using UnityEngine;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
[ExecuteAlways]
|
||||
[RequireComponent(typeof(Light))]
|
||||
public class MenuLightAnimator : MonoBehaviour
|
||||
{
|
||||
[Header("Rotation")]
|
||||
// Yaw oscillates around the base direction rather than spinning all the way around, so the
|
||||
// light never swings past the wall's edge into a back-lighting angle that goes dark.
|
||||
public float yawAmplitude = 35f;
|
||||
public float yawSpeed = 0.2f;
|
||||
public float pitchAmplitude = 10f;
|
||||
public float pitchSpeed = 0.35f;
|
||||
|
||||
[Header("Intensity & Color")]
|
||||
public float baseIntensity = 1.1f;
|
||||
public float intensityPulseAmount = 0.25f;
|
||||
public float pulseSpeed = 0.6f;
|
||||
public Color colorA = new Color(1f, 0.96f, 0.86f);
|
||||
public Color colorB = new Color(0.8f, 0.88f, 1f);
|
||||
|
||||
Light _light;
|
||||
float _baseYaw;
|
||||
float _basePitch;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_light = GetComponent<Light>();
|
||||
Vector3 e = transform.eulerAngles;
|
||||
_baseYaw = e.y;
|
||||
_basePitch = e.x;
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
if (!Application.isPlaying)
|
||||
EditorApplication.update += EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
void EditorTick()
|
||||
{
|
||||
if (Application.isPlaying) return;
|
||||
Animate((float)EditorApplication.timeSinceStartup);
|
||||
}
|
||||
#endif
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!Application.isPlaying) return;
|
||||
Animate(Time.time);
|
||||
}
|
||||
|
||||
void Animate(float time)
|
||||
{
|
||||
float yaw = _baseYaw + Mathf.Sin(time * yawSpeed) * yawAmplitude;
|
||||
float pitch = _basePitch + Mathf.Sin(time * pitchSpeed + 1.3f) * pitchAmplitude;
|
||||
transform.rotation = Quaternion.Euler(pitch, yaw, 0f);
|
||||
|
||||
if (_light == null) _light = GetComponent<Light>();
|
||||
_light.intensity = baseIntensity + Mathf.Sin(time * pulseSpeed) * intensityPulseAmount;
|
||||
float colorT = (Mathf.Sin(time * pulseSpeed * 0.5f) + 1f) * 0.5f;
|
||||
_light.color = Color.Lerp(colorA, colorB, colorT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9ff347d60077f4b47982b9f52057b495
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a02483efa368f554c85512e155492f99
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,304 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace Procedural
|
||||
{
|
||||
[ExecuteAlways]
|
||||
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
|
||||
public class LowPolyTriangleField : MonoBehaviour
|
||||
{
|
||||
[Header("Grid")]
|
||||
[Min(1)] public int columns = 24;
|
||||
[Min(1)] public int rows = 14;
|
||||
public float cellSize = 1.5f;
|
||||
[Range(0f, 0.5f)] public float jitterAmount = 0.35f;
|
||||
|
||||
[Header("Static Shape")]
|
||||
public float noiseScale = 0.12f;
|
||||
public float heightAmplitude = 1.2f;
|
||||
|
||||
[Header("Wave Animation")]
|
||||
public bool animate = true;
|
||||
public float waveAmplitude = 0.25f;
|
||||
public float waveFrequency = 0.25f;
|
||||
public float waveSpeed = 0.6f;
|
||||
|
||||
[Header("Edges")]
|
||||
public float edgeWidth = 0.06f;
|
||||
public float edgeHeightOffset = 0.02f;
|
||||
|
||||
[Header("Materials")]
|
||||
public Material faceMaterial;
|
||||
public Material edgeMaterial;
|
||||
|
||||
[Header("Random")]
|
||||
public int seed = 12345;
|
||||
|
||||
Mesh _mesh;
|
||||
MeshFilter _meshFilter;
|
||||
|
||||
Vector2[] _gridXZ;
|
||||
float[] _staticHeight;
|
||||
Vector3[] _gridNormalAccum;
|
||||
int[] _gridNormalCount;
|
||||
List<int[]> _triangles;
|
||||
List<(int a, int b)> _uniqueEdges;
|
||||
|
||||
Vector3[] _facePositions;
|
||||
Vector3[] _faceNormals;
|
||||
int[] _faceIndices;
|
||||
|
||||
Vector3[] _edgePositions;
|
||||
int[] _edgeIndices;
|
||||
|
||||
bool _topologyDirty = true;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_meshFilter = GetComponent<MeshFilter>();
|
||||
RebuildTopology();
|
||||
UpdateGeometry(0f);
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
if (!Application.isPlaying)
|
||||
EditorApplication.update += EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnValidate()
|
||||
{
|
||||
_topologyDirty = true;
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
void EditorTick()
|
||||
{
|
||||
if (Application.isPlaying) return;
|
||||
if (_topologyDirty) RebuildTopology();
|
||||
if (animate) UpdateGeometry((float)EditorApplication.timeSinceStartup);
|
||||
if (this != null) EditorUtility.SetDirty(this);
|
||||
}
|
||||
#endif
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!Application.isPlaying) return;
|
||||
if (_topologyDirty) RebuildTopology();
|
||||
if (animate) UpdateGeometry(Time.time);
|
||||
}
|
||||
|
||||
void RebuildTopology()
|
||||
{
|
||||
_topologyDirty = false;
|
||||
|
||||
int vertsX = columns + 1;
|
||||
int vertsZ = rows + 1;
|
||||
int gridCount = vertsX * vertsZ;
|
||||
|
||||
_gridXZ = new Vector2[gridCount];
|
||||
_staticHeight = new float[gridCount];
|
||||
|
||||
var rng = new System.Random(seed);
|
||||
float originX = -columns * cellSize * 0.5f;
|
||||
float originZ = -rows * cellSize * 0.5f;
|
||||
|
||||
for (int j = 0; j < vertsZ; j++)
|
||||
{
|
||||
for (int i = 0; i < vertsX; i++)
|
||||
{
|
||||
int idx = j * vertsX + i;
|
||||
bool border = i == 0 || i == columns || j == 0 || j == rows;
|
||||
float jitterX = border ? 0f : ((float)rng.NextDouble() * 2f - 1f) * jitterAmount * cellSize;
|
||||
float jitterZ = border ? 0f : ((float)rng.NextDouble() * 2f - 1f) * jitterAmount * cellSize;
|
||||
|
||||
float x = originX + i * cellSize + jitterX;
|
||||
float z = originZ + j * cellSize + jitterZ;
|
||||
_gridXZ[idx] = new Vector2(x, z);
|
||||
|
||||
float n = Mathf.PerlinNoise(x * noiseScale + seed * 0.017f, z * noiseScale + seed * 0.017f);
|
||||
_staticHeight[idx] = (n * 2f - 1f) * heightAmplitude;
|
||||
}
|
||||
}
|
||||
|
||||
_triangles = new List<int[]>(columns * rows * 2);
|
||||
var edgeSet = new HashSet<(int, int)>();
|
||||
_uniqueEdges = new List<(int, int)>();
|
||||
|
||||
for (int j = 0; j < rows; j++)
|
||||
{
|
||||
for (int i = 0; i < columns; i++)
|
||||
{
|
||||
int i00 = j * vertsX + i;
|
||||
int i10 = j * vertsX + (i + 1);
|
||||
int i01 = (j + 1) * vertsX + i;
|
||||
int i11 = (j + 1) * vertsX + (i + 1);
|
||||
|
||||
bool flip = rng.Next(2) == 0;
|
||||
|
||||
if (flip)
|
||||
{
|
||||
AddTriangle(i00, i11, i01, edgeSet);
|
||||
AddTriangle(i00, i10, i11, edgeSet);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddTriangle(i00, i10, i01, edgeSet);
|
||||
AddTriangle(i10, i11, i01, edgeSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int faceVertCount = _triangles.Count * 3;
|
||||
_facePositions = new Vector3[faceVertCount];
|
||||
_faceNormals = new Vector3[faceVertCount];
|
||||
_faceIndices = new int[faceVertCount];
|
||||
for (int k = 0; k < faceVertCount; k++) _faceIndices[k] = k;
|
||||
|
||||
int edgeVertCount = _uniqueEdges.Count * 4;
|
||||
_edgePositions = new Vector3[edgeVertCount];
|
||||
_edgeIndices = new int[_uniqueEdges.Count * 6];
|
||||
for (int e = 0; e < _uniqueEdges.Count; e++)
|
||||
{
|
||||
int b = e * 4;
|
||||
int t = e * 6;
|
||||
_edgeIndices[t + 0] = b + 0;
|
||||
_edgeIndices[t + 1] = b + 2;
|
||||
_edgeIndices[t + 2] = b + 1;
|
||||
_edgeIndices[t + 3] = b + 1;
|
||||
_edgeIndices[t + 4] = b + 2;
|
||||
_edgeIndices[t + 5] = b + 3;
|
||||
}
|
||||
|
||||
_gridNormalAccum = new Vector3[gridCount];
|
||||
_gridNormalCount = new int[gridCount];
|
||||
|
||||
if (_mesh == null)
|
||||
{
|
||||
_mesh = new Mesh { name = "LowPolyTriangleField" };
|
||||
_mesh.MarkDynamic();
|
||||
}
|
||||
_mesh.indexFormat = (faceVertCount + edgeVertCount) > 60000
|
||||
? UnityEngine.Rendering.IndexFormat.UInt32
|
||||
: UnityEngine.Rendering.IndexFormat.UInt16;
|
||||
_mesh.Clear();
|
||||
_meshFilter.sharedMesh = _mesh;
|
||||
|
||||
var renderer = GetComponent<MeshRenderer>();
|
||||
renderer.sharedMaterials = new[] { faceMaterial, edgeMaterial };
|
||||
|
||||
void AddTriangle(int a, int b2, int c, HashSet<(int, int)> edges)
|
||||
{
|
||||
_triangles.Add(new[] { a, b2, c });
|
||||
AddEdge(a, b2, edges);
|
||||
AddEdge(b2, c, edges);
|
||||
AddEdge(c, a, edges);
|
||||
}
|
||||
|
||||
void AddEdge(int a, int b2, HashSet<(int, int)> edges)
|
||||
{
|
||||
var key = a < b2 ? (a, b2) : (b2, a);
|
||||
if (edges.Add(key)) _uniqueEdges.Add(key);
|
||||
}
|
||||
}
|
||||
|
||||
void UpdateGeometry(float time)
|
||||
{
|
||||
if (_gridXZ == null) return;
|
||||
|
||||
int gridCount = _gridXZ.Length;
|
||||
var pos = new Vector3[gridCount];
|
||||
for (int idx = 0; idx < gridCount; idx++)
|
||||
{
|
||||
var xz = _gridXZ[idx];
|
||||
float wave = 0f;
|
||||
if (animate)
|
||||
{
|
||||
wave = waveAmplitude * 0.5f * (
|
||||
Mathf.Sin((xz.x + xz.y) * waveFrequency + time * waveSpeed) +
|
||||
Mathf.Sin((xz.x - xz.y) * waveFrequency * 0.7f + time * waveSpeed * 1.3f));
|
||||
}
|
||||
pos[idx] = new Vector3(xz.x, _staticHeight[idx] + wave, xz.y);
|
||||
_gridNormalAccum[idx] = Vector3.zero;
|
||||
_gridNormalCount[idx] = 0;
|
||||
}
|
||||
|
||||
for (int t = 0; t < _triangles.Count; t++)
|
||||
{
|
||||
var tri = _triangles[t];
|
||||
Vector3 v0 = pos[tri[0]];
|
||||
Vector3 v1 = pos[tri[1]];
|
||||
Vector3 v2 = pos[tri[2]];
|
||||
Vector3 normal = Vector3.Cross(v1 - v0, v2 - v0).normalized;
|
||||
|
||||
int b = t * 3;
|
||||
_facePositions[b + 0] = v0;
|
||||
_facePositions[b + 1] = v1;
|
||||
_facePositions[b + 2] = v2;
|
||||
_faceNormals[b + 0] = normal;
|
||||
_faceNormals[b + 1] = normal;
|
||||
_faceNormals[b + 2] = normal;
|
||||
|
||||
_gridNormalAccum[tri[0]] += normal; _gridNormalCount[tri[0]]++;
|
||||
_gridNormalAccum[tri[1]] += normal; _gridNormalCount[tri[1]]++;
|
||||
_gridNormalAccum[tri[2]] += normal; _gridNormalCount[tri[2]]++;
|
||||
}
|
||||
|
||||
for (int e = 0; e < _uniqueEdges.Count; e++)
|
||||
{
|
||||
var (a, bIdx) = _uniqueEdges[e];
|
||||
Vector3 p0 = pos[a];
|
||||
Vector3 p1 = pos[bIdx];
|
||||
Vector3 n0 = _gridNormalCount[a] > 0 ? (_gridNormalAccum[a] / _gridNormalCount[a]).normalized : Vector3.up;
|
||||
Vector3 n1 = _gridNormalCount[bIdx] > 0 ? (_gridNormalAccum[bIdx] / _gridNormalCount[bIdx]).normalized : Vector3.up;
|
||||
|
||||
Vector3 dir = (p1 - p0).normalized;
|
||||
Vector3 avgNormal = (n0 + n1).normalized;
|
||||
Vector3 side = Vector3.Cross(dir, avgNormal).normalized * (edgeWidth * 0.5f);
|
||||
|
||||
Vector3 p0Off = p0 + n0 * edgeHeightOffset;
|
||||
Vector3 p1Off = p1 + n1 * edgeHeightOffset;
|
||||
|
||||
int b = e * 4;
|
||||
_edgePositions[b + 0] = p0Off - side;
|
||||
_edgePositions[b + 1] = p0Off + side;
|
||||
_edgePositions[b + 2] = p1Off - side;
|
||||
_edgePositions[b + 3] = p1Off + side;
|
||||
}
|
||||
|
||||
_mesh.subMeshCount = 2;
|
||||
_mesh.SetVertices(_facePositions.Length > 0 ? Concat(_facePositions, _edgePositions) : _edgePositions);
|
||||
|
||||
int faceVertCount = _facePositions.Length;
|
||||
var normals = new Vector3[faceVertCount + _edgePositions.Length];
|
||||
for (int i = 0; i < faceVertCount; i++) normals[i] = _faceNormals[i];
|
||||
for (int i = 0; i < _edgePositions.Length; i++) normals[faceVertCount + i] = Vector3.up;
|
||||
_mesh.SetNormals(normals);
|
||||
|
||||
_mesh.SetIndices(_faceIndices, MeshTopology.Triangles, 0, false);
|
||||
|
||||
var offsetEdgeIndices = new int[_edgeIndices.Length];
|
||||
for (int i = 0; i < _edgeIndices.Length; i++) offsetEdgeIndices[i] = _edgeIndices[i] + faceVertCount;
|
||||
_mesh.SetIndices(offsetEdgeIndices, MeshTopology.Triangles, 1, false);
|
||||
|
||||
_mesh.RecalculateBounds();
|
||||
}
|
||||
|
||||
static Vector3[] Concat(Vector3[] a, Vector3[] b)
|
||||
{
|
||||
var result = new Vector3[a.Length + b.Length];
|
||||
a.CopyTo(result, 0);
|
||||
b.CopyTo(result, a.Length);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d98243f3b31761c45a022724b517c3df
|
||||
@@ -0,0 +1,394 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace Procedural
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds a panel out of individual equilateral-triangle GameObjects tiled edge-to-edge.
|
||||
/// Each tile is its own mesh/transform; a shared driver moves every tile's transform
|
||||
/// independently each frame so the panel reads as a wave, rather than deforming one mesh.
|
||||
/// </summary>
|
||||
[ExecuteAlways]
|
||||
public class TriangleWavePanel : MonoBehaviour
|
||||
{
|
||||
[Header("Grid")]
|
||||
[Min(1)] public int columns = 14;
|
||||
[Min(1)] public int rows = 10;
|
||||
public float triangleSize = 1.2f;
|
||||
[Range(0.5f, 1f)] public float gapScale = 1f;
|
||||
|
||||
[Header("Volume & Corner Chamfer")]
|
||||
public float thickness = 0.18f;
|
||||
[Range(0f, 0.4f)] public float cornerRadius = 0f;
|
||||
[Range(1, 8)] public int cornerSegments = 1;
|
||||
|
||||
[Header("Wave")]
|
||||
public bool animate = true;
|
||||
public float waveAmplitude = 0.22f;
|
||||
public float waveFrequency = 0.35f;
|
||||
public float waveSpeed = 1.1f;
|
||||
[Range(0f, 20f)] public float tiltAmount = 5f;
|
||||
|
||||
[Header("Panel Sway (whole-panel rotation)")]
|
||||
[Range(0f, 45f)] public float swayAmplitude = 0f;
|
||||
public float swaySpeed = 0.2f;
|
||||
|
||||
[Header("Backer (fills the gaps)")]
|
||||
public bool showBacker = true;
|
||||
public float backerOffset = -0.4f;
|
||||
public float backerPadding = 1.5f;
|
||||
|
||||
[Header("Materials")]
|
||||
public Material faceMaterial;
|
||||
public Material backerMaterial;
|
||||
|
||||
Transform[] _tileTransforms;
|
||||
Vector3[] _tileBasePos;
|
||||
Quaternion _baseRotation;
|
||||
bool _dirty = true;
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
_baseRotation = transform.localRotation;
|
||||
Rebuild();
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
if (!Application.isPlaying)
|
||||
EditorApplication.update += EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= EditorTick;
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnValidate()
|
||||
{
|
||||
_dirty = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forces an immediate rebuild. Needed after configuring fields via code (e.g. from an
|
||||
/// editor script right after AddComponent), since plain field writes don't route through
|
||||
/// OnValidate the way Inspector edits do, so _dirty never flips back on by itself.
|
||||
/// </summary>
|
||||
public void RebuildNow()
|
||||
{
|
||||
_baseRotation = transform.localRotation;
|
||||
Rebuild();
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
void EditorTick()
|
||||
{
|
||||
if (Application.isPlaying) return;
|
||||
if (_dirty) Rebuild();
|
||||
if (animate) AnimateTiles((float)EditorApplication.timeSinceStartup);
|
||||
}
|
||||
#endif
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!Application.isPlaying) return;
|
||||
if (_dirty) Rebuild();
|
||||
if (animate) AnimateTiles(Time.time);
|
||||
}
|
||||
|
||||
void Rebuild()
|
||||
{
|
||||
_dirty = false;
|
||||
ClearChildren();
|
||||
|
||||
float s = triangleSize;
|
||||
float h = s * Mathf.Sqrt(3f) * 0.5f;
|
||||
|
||||
Mesh upMesh = BuildRoundedTrianglePrism(
|
||||
new Vector2(-s * 0.5f, -h / 3f),
|
||||
new Vector2(s * 0.5f, -h / 3f),
|
||||
new Vector2(0f, 2f * h / 3f),
|
||||
gapScale, cornerRadius, cornerSegments, thickness, "TrianglePanel_Up");
|
||||
|
||||
Mesh downMesh = BuildRoundedTrianglePrism(
|
||||
new Vector2(-s * 0.5f, h / 3f),
|
||||
new Vector2(s * 0.5f, h / 3f),
|
||||
new Vector2(0f, -2f * h / 3f),
|
||||
gapScale, cornerRadius, cornerSegments, thickness, "TrianglePanel_Down");
|
||||
|
||||
float originX = -(columns * s) * 0.5f;
|
||||
float originZ = -(rows * h) * 0.5f;
|
||||
|
||||
var transforms = new List<Transform>(columns * rows * 2);
|
||||
var basePositions = new List<Vector3>(columns * rows * 2);
|
||||
|
||||
for (int r = 0; r < rows; r++)
|
||||
{
|
||||
for (int c = 0; c < columns; c++)
|
||||
{
|
||||
float rowZ = originZ + r * h;
|
||||
|
||||
Vector3 upPos = new Vector3(originX + c * s + s * 0.5f, 0f, rowZ + h / 3f);
|
||||
CreateTile($"Tile_{r}_{c}_Up", upMesh, upPos, transforms, basePositions);
|
||||
|
||||
Vector3 downPos = new Vector3(originX + c * s + s, 0f, rowZ + 2f * h / 3f);
|
||||
CreateTile($"Tile_{r}_{c}_Down", downMesh, downPos, transforms, basePositions);
|
||||
}
|
||||
}
|
||||
|
||||
_tileTransforms = transforms.ToArray();
|
||||
_tileBasePos = basePositions.ToArray();
|
||||
|
||||
if (showBacker)
|
||||
BuildBacker(originX, originZ, s, h);
|
||||
|
||||
AnimateTiles(0f);
|
||||
}
|
||||
|
||||
void CreateTile(string tileName, Mesh mesh, Vector3 localPos, List<Transform> transforms, List<Vector3> basePositions)
|
||||
{
|
||||
var go = new GameObject(tileName);
|
||||
go.transform.SetParent(transform, false);
|
||||
go.transform.localPosition = localPos;
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var mr = go.AddComponent<MeshRenderer>();
|
||||
mr.sharedMaterial = faceMaterial;
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
transforms.Add(go.transform);
|
||||
basePositions.Add(localPos);
|
||||
}
|
||||
|
||||
void BuildBacker(float originX, float originZ, float s, float h)
|
||||
{
|
||||
var go = new GameObject("Backer");
|
||||
go.transform.SetParent(transform, false);
|
||||
float width = columns * s + backerPadding * 2f;
|
||||
float depth = rows * h + backerPadding * 2f;
|
||||
float cx = originX + (columns * s) * 0.5f;
|
||||
float cz = originZ + (rows * h) * 0.5f;
|
||||
go.transform.localPosition = new Vector3(cx, backerOffset, cz);
|
||||
|
||||
var mesh = new Mesh { name = "TrianglePanel_Backer" };
|
||||
float hw = width * 0.5f;
|
||||
float hd = depth * 0.5f;
|
||||
mesh.vertices = new[]
|
||||
{
|
||||
new Vector3(-hw, 0f, -hd),
|
||||
new Vector3(hw, 0f, -hd),
|
||||
new Vector3(-hw, 0f, hd),
|
||||
new Vector3(hw, 0f, hd),
|
||||
};
|
||||
mesh.triangles = new[] { 0, 2, 1, 1, 2, 3 };
|
||||
mesh.normals = new[] { Vector3.up, Vector3.up, Vector3.up, Vector3.up };
|
||||
mesh.RecalculateBounds();
|
||||
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var mr = go.AddComponent<MeshRenderer>();
|
||||
mr.sharedMaterial = backerMaterial;
|
||||
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
}
|
||||
|
||||
static Mesh BuildRoundedTrianglePrism(Vector2 a, Vector2 b, Vector2 c, float gapScale, float requestedRadius,
|
||||
int cornerSegments, float thickness, string meshName)
|
||||
{
|
||||
Vector2[] pts = { a * gapScale, b * gapScale, c * gapScale };
|
||||
|
||||
float minEdge = Mathf.Min(
|
||||
Vector2.Distance(pts[0], pts[1]),
|
||||
Mathf.Min(Vector2.Distance(pts[1], pts[2]), Vector2.Distance(pts[2], pts[0])));
|
||||
float radius = Mathf.Clamp(requestedRadius, 0f, minEdge * 0.28f);
|
||||
|
||||
List<Vector2> outline = RoundedTriangleOutline(pts, radius, cornerSegments);
|
||||
int n = outline.Count;
|
||||
float halfT = thickness * 0.5f;
|
||||
|
||||
var vertices = new List<Vector3>(n * 4 + 2);
|
||||
var normals = new List<Vector3>(n * 4 + 2);
|
||||
var triangles = new List<int>(n * 12);
|
||||
|
||||
int topCenter = vertices.Count;
|
||||
vertices.Add(new Vector3(0f, halfT, 0f));
|
||||
normals.Add(Vector3.up);
|
||||
int topStart = vertices.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
vertices.Add(new Vector3(outline[i].x, halfT, outline[i].y));
|
||||
normals.Add(Vector3.up);
|
||||
}
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
triangles.Add(topCenter);
|
||||
triangles.Add(topStart + i);
|
||||
triangles.Add(topStart + (i + 1) % n);
|
||||
}
|
||||
|
||||
int bottomCenter = vertices.Count;
|
||||
vertices.Add(new Vector3(0f, -halfT, 0f));
|
||||
normals.Add(Vector3.down);
|
||||
int bottomStart = vertices.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
vertices.Add(new Vector3(outline[i].x, -halfT, outline[i].y));
|
||||
normals.Add(Vector3.down);
|
||||
}
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
triangles.Add(bottomCenter);
|
||||
triangles.Add(bottomStart + (i + 1) % n);
|
||||
triangles.Add(bottomStart + i);
|
||||
}
|
||||
|
||||
int sideTopStart = vertices.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Vector2 p = outline[i];
|
||||
Vector3 outward = new Vector3(p.x, 0f, p.y);
|
||||
outward = outward.sqrMagnitude > 0.0001f ? outward.normalized : Vector3.forward;
|
||||
vertices.Add(new Vector3(p.x, halfT, p.y));
|
||||
normals.Add(outward);
|
||||
}
|
||||
int sideBottomStart = vertices.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Vector2 p = outline[i];
|
||||
Vector3 outward = new Vector3(p.x, 0f, p.y);
|
||||
outward = outward.sqrMagnitude > 0.0001f ? outward.normalized : Vector3.forward;
|
||||
vertices.Add(new Vector3(p.x, -halfT, p.y));
|
||||
normals.Add(outward);
|
||||
}
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int next = (i + 1) % n;
|
||||
int t0 = sideTopStart + i;
|
||||
int t1 = sideTopStart + next;
|
||||
int b0 = sideBottomStart + i;
|
||||
int b1 = sideBottomStart + next;
|
||||
triangles.Add(t0); triangles.Add(b0); triangles.Add(t1);
|
||||
triangles.Add(t1); triangles.Add(b0); triangles.Add(b1);
|
||||
}
|
||||
|
||||
var mesh = new Mesh { name = meshName };
|
||||
mesh.SetVertices(vertices);
|
||||
mesh.SetNormals(normals);
|
||||
mesh.SetTriangles(triangles, 0);
|
||||
mesh.RecalculateBounds();
|
||||
return mesh;
|
||||
}
|
||||
|
||||
static List<Vector2> RoundedTriangleOutline(Vector2[] pts, float radius, int segments)
|
||||
{
|
||||
var outline = new List<Vector2>();
|
||||
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
Vector2 v = pts[k];
|
||||
|
||||
if (radius < 0.0001f)
|
||||
{
|
||||
outline.Add(v);
|
||||
continue;
|
||||
}
|
||||
|
||||
Vector2 prev = pts[(k + 2) % 3];
|
||||
Vector2 next = pts[(k + 1) % 3];
|
||||
|
||||
Vector2 dirToPrev = (prev - v).normalized;
|
||||
Vector2 dirToNext = (next - v).normalized;
|
||||
|
||||
float dot = Mathf.Clamp(Vector2.Dot(dirToPrev, dirToNext), -1f, 1f);
|
||||
float angle = Mathf.Acos(dot);
|
||||
float halfAngle = angle * 0.5f;
|
||||
float tangentDist = radius / Mathf.Tan(halfAngle);
|
||||
float centerDist = radius / Mathf.Sin(halfAngle);
|
||||
|
||||
Vector2 bisector = dirToPrev + dirToNext;
|
||||
bisector = bisector.sqrMagnitude > 0.0001f ? bisector.normalized : dirToPrev;
|
||||
|
||||
Vector2 tangentOnPrevEdge = v + dirToPrev * tangentDist;
|
||||
Vector2 tangentOnNextEdge = v + dirToNext * tangentDist;
|
||||
Vector2 center = v + bisector * centerDist;
|
||||
|
||||
Vector2 startDir = (tangentOnPrevEdge - center).normalized;
|
||||
Vector2 endDir = (tangentOnNextEdge - center).normalized;
|
||||
|
||||
float cross = startDir.x * endDir.y - startDir.y * endDir.x;
|
||||
float sweepSign = cross >= 0f ? 1f : -1f;
|
||||
float sweepAngle = Mathf.Acos(Mathf.Clamp(Vector2.Dot(startDir, endDir), -1f, 1f));
|
||||
|
||||
int segs = Mathf.Max(1, segments);
|
||||
for (int seg = 0; seg <= segs; seg++)
|
||||
{
|
||||
float t = (float)seg / segs;
|
||||
float a = sweepSign * sweepAngle * t;
|
||||
float ca = Mathf.Cos(a), sa = Mathf.Sin(a);
|
||||
Vector2 rotated = new Vector2(
|
||||
startDir.x * ca - startDir.y * sa,
|
||||
startDir.x * sa + startDir.y * ca);
|
||||
outline.Add(center + rotated * radius);
|
||||
}
|
||||
}
|
||||
|
||||
return outline;
|
||||
}
|
||||
|
||||
void AnimateTiles(float time)
|
||||
{
|
||||
if (swayAmplitude > 0.001f && animate)
|
||||
{
|
||||
float sway = Mathf.Sin(time * swaySpeed) * swayAmplitude;
|
||||
// Rotate around the world Y axis on top of whatever base orientation the panel
|
||||
// was authored with (e.g. tipped vertical), rather than a local axis, so the sway
|
||||
// always reads as a gentle turn regardless of how the panel itself is oriented.
|
||||
transform.localRotation = Quaternion.AngleAxis(sway, Vector3.up) * _baseRotation;
|
||||
}
|
||||
else
|
||||
{
|
||||
transform.localRotation = _baseRotation;
|
||||
}
|
||||
|
||||
if (_tileTransforms == null) return;
|
||||
float t = time * waveSpeed;
|
||||
|
||||
for (int i = 0; i < _tileTransforms.Length; i++)
|
||||
{
|
||||
var tf = _tileTransforms[i];
|
||||
if (tf == null) continue;
|
||||
var b = _tileBasePos[i];
|
||||
|
||||
float sum = (b.x + b.z) * waveFrequency;
|
||||
float diff = (b.x - b.z) * waveFrequency * 0.7f;
|
||||
|
||||
float wave = animate
|
||||
? waveAmplitude * 0.5f * (Mathf.Sin(sum + t) + Mathf.Sin(diff + t * 1.3f))
|
||||
: 0f;
|
||||
|
||||
tf.localPosition = new Vector3(b.x, b.y + wave, b.z);
|
||||
|
||||
if (tiltAmount > 0f && animate)
|
||||
{
|
||||
float tiltX = tiltAmount * Mathf.Cos(diff + t * 1.3f);
|
||||
float tiltZ = tiltAmount * Mathf.Cos(sum + t);
|
||||
tf.localRotation = Quaternion.Euler(tiltX, 0f, -tiltZ);
|
||||
}
|
||||
else
|
||||
{
|
||||
tf.localRotation = Quaternion.identity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ClearChildren()
|
||||
{
|
||||
for (int i = transform.childCount - 1; i >= 0; i--)
|
||||
{
|
||||
var child = transform.GetChild(i).gameObject;
|
||||
if (Application.isPlaying) Destroy(child);
|
||||
else DestroyImmediate(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5476e1f1daded4d4f82d503bb03be2d3
|
||||
@@ -0,0 +1,102 @@
|
||||
using Mirror;
|
||||
using Rive;
|
||||
using Rive.Components;
|
||||
using TMPro;
|
||||
using UnityEngine;
|
||||
|
||||
public class RiveLoginController : MonoBehaviour
|
||||
{
|
||||
[Header("Rive")]
|
||||
[SerializeField] private RiveWidget riveWidget;
|
||||
[SerializeField] private string startTriggerName = "startClicked";
|
||||
|
||||
[Header("Login")]
|
||||
[Tooltip("Still needed username until Rive has a bound string property.")]
|
||||
[SerializeField] private TMP_InputField usernameInput;
|
||||
|
||||
[SerializeField] private LoginUI loginUI;
|
||||
|
||||
private ViewModelInstanceTriggerProperty startTrigger;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (riveWidget == null)
|
||||
riveWidget = GetComponent<RiveWidget>();
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (riveWidget == null) return;
|
||||
|
||||
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
|
||||
HandleWidgetStatusChanged();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (riveWidget != null)
|
||||
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
|
||||
|
||||
if (startTrigger != null)
|
||||
startTrigger.OnTriggered -= OnStartClicked;
|
||||
}
|
||||
|
||||
private void HandleWidgetStatusChanged()
|
||||
{
|
||||
if (riveWidget.Status != WidgetStatus.Loaded)
|
||||
return;
|
||||
|
||||
ViewModelInstance vm = riveWidget.StateMachine?.ViewModelInstance;
|
||||
if (vm == null)
|
||||
{
|
||||
Debug.LogError("RiveLoginController: ViewModelInstance is null. Set Data Binding Mode to Auto Bind Default.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (startTrigger != null)
|
||||
startTrigger.OnTriggered -= OnStartClicked;
|
||||
|
||||
startTrigger = vm.GetTriggerProperty(startTriggerName);
|
||||
if (startTrigger == null)
|
||||
{
|
||||
Debug.LogError($"RiveLoginController: Trigger '{startTriggerName}' not found.");
|
||||
return;
|
||||
}
|
||||
|
||||
startTrigger.OnTriggered += OnStartClicked;
|
||||
}
|
||||
|
||||
private void OnStartClicked()
|
||||
{
|
||||
StartMultiplayerSession();
|
||||
}
|
||||
|
||||
public void StartMultiplayerSession()
|
||||
{
|
||||
string username = usernameInput != null
|
||||
? usernameInput.text.Trim()
|
||||
: string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
{
|
||||
if (loginUI != null && loginUI.errorText != null)
|
||||
{
|
||||
loginUI.errorText.text = "Enter a username";
|
||||
loginUI.errorText.gameObject.SetActive(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning("RiveLoginController: Username is empty");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ChatAuthenticator auth = NetworkManager.singleton.GetComponent<ChatAuthenticator>();
|
||||
if (auth != null)
|
||||
auth.SetPlayerName(username);
|
||||
else
|
||||
Debug.LogWarning("RiveLoginController: ChatAuthenticator not found on NetworkManager");
|
||||
|
||||
NetworkManager.singleton.StartClient();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3fe02973c43b80c438b8634ba5fc2153
|
||||
@@ -0,0 +1,132 @@
|
||||
using ProceduralEditor;
|
||||
using Rive;
|
||||
using Rive.Components;
|
||||
using System.Reflection.Metadata;
|
||||
using UnityEngine;
|
||||
using UnityEngine.InputSystem;
|
||||
|
||||
/// Sends keyboard navigation commands to the Rive menu and
|
||||
/// activates the Play option when Enter is pressed
|
||||
public class RiveNavigationController : MonoBehaviour
|
||||
{
|
||||
[Header("Rive")]
|
||||
[Tooltip("RiveWidget that hosts the menu artboard.")]
|
||||
[SerializeField] private RiveWidget riveWidget;
|
||||
|
||||
[Header("Scene Transition")]
|
||||
[Tooltip("Object containing the SceneTransitionController component.")]
|
||||
[SerializeField] private SceneTransitionController sceneTransitionController;
|
||||
|
||||
[Header("Menu Selection")]
|
||||
[Tooltip("Total number of selectable Rive menu buttons.")]
|
||||
[Min(1)]
|
||||
[SerializeField] private int menuItemCount = 1;
|
||||
|
||||
|
||||
private const string NextTriggerName = "nextButtonClicked";
|
||||
private const string PreviousTriggerName = "previousButtonClicked";
|
||||
private const int PlayIndex = 0;
|
||||
|
||||
private ViewModelInstanceTriggerProperty nextTrigger;
|
||||
private ViewModelInstanceTriggerProperty previousTrigger;
|
||||
|
||||
private int selectedIndex;
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
if (riveWidget == null)
|
||||
{
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: riveWidget is not assigned.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (sceneTransitionController == null)
|
||||
{
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: SceneTransitionController is not assigned.");
|
||||
}
|
||||
|
||||
riveWidget.OnWidgetStatusChanged += HandleWidgetStatusChanged;
|
||||
// In case the widget already finished loading before we subscribed.
|
||||
HandleWidgetStatusChanged();
|
||||
}
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (riveWidget != null)
|
||||
riveWidget.OnWidgetStatusChanged -= HandleWidgetStatusChanged;
|
||||
}
|
||||
|
||||
private void HandleWidgetStatusChanged()
|
||||
{
|
||||
if (riveWidget.Status != WidgetStatus.Loaded)
|
||||
return;
|
||||
|
||||
ViewModelInstance viewModelInstance = riveWidget.StateMachine?.ViewModelInstance;
|
||||
if (viewModelInstance == null)
|
||||
{
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: ViewModelInstance is null. " +
|
||||
"Set Data Binding Mode to Auto Bind Default on the Rive Widget.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Cache both triggers once the artboard is ready so Update() doesn't do
|
||||
// string lookups every frame.
|
||||
nextTrigger = viewModelInstance.GetTriggerProperty(NextTriggerName);
|
||||
previousTrigger = viewModelInstance.GetTriggerProperty(PreviousTriggerName);
|
||||
|
||||
if (nextTrigger == null)
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: Trigger '{NextTriggerName}' not found on view model.");
|
||||
if (previousTrigger == null)
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: Trigger '{PreviousTriggerName}' not found on view model.");
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Keyboard keyboard = Keyboard.current;
|
||||
|
||||
if (keyboard == null)
|
||||
return;
|
||||
|
||||
if (keyboard.rightArrowKey.wasPressedThisFrame)
|
||||
{
|
||||
MoveSelection(+1);
|
||||
nextTrigger?.Trigger();
|
||||
}
|
||||
|
||||
if (keyboard.leftArrowKey.wasPressedThisFrame)
|
||||
{
|
||||
MoveSelection(-1);
|
||||
previousTrigger?.Trigger();
|
||||
}
|
||||
|
||||
bool enterPressed = keyboard.enterKey.wasPressedThisFrame || keyboard.numpadEnterKey.wasPressedThisFrame;
|
||||
|
||||
if (enterPressed && selectedIndex == PlayIndex)
|
||||
{
|
||||
if (sceneTransitionController == null)
|
||||
{
|
||||
Debug.LogError($"{nameof(RiveNavigationController)}: SceneTransitionController is not assigned.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
sceneTransitionController.LoadGameplayScene();
|
||||
}
|
||||
}
|
||||
|
||||
private void MoveSelection(int direction)
|
||||
{
|
||||
if (menuItemCount <= 0)
|
||||
return;
|
||||
|
||||
selectedIndex += direction;
|
||||
|
||||
if (selectedIndex >= menuItemCount)
|
||||
selectedIndex = 0;
|
||||
|
||||
if (selectedIndex < 0)
|
||||
selectedIndex = menuItemCount - 1;
|
||||
|
||||
Debug.Log($"Rive menu selection index: {selectedIndex}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7da53f31be2464b45ada2a0875845057
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace ProceduralEditor
|
||||
{
|
||||
public class SceneTransitionController : MonoBehaviour
|
||||
{
|
||||
const string GameplaySceneName = "Landscape";
|
||||
|
||||
[Header("Fade")]
|
||||
[Tooltip("CanvasGroup on the Fade Image object.")]
|
||||
[SerializeField] private CanvasGroup fadeGroup;
|
||||
|
||||
[Min(0f)]
|
||||
[SerializeField] private float fadeDuration = 0.75f;
|
||||
|
||||
private bool transitionInProgress;
|
||||
|
||||
public void LoadGameplayScene()
|
||||
{
|
||||
if (transitionInProgress)
|
||||
return;
|
||||
|
||||
if (fadeGroup == null)
|
||||
{
|
||||
Debug.LogError($"{nameof(SceneTransitionController)}: Fade Group is not assigned.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
transitionInProgress = true;
|
||||
StartCoroutine(FadeThenLoadGameplayScene());
|
||||
}
|
||||
|
||||
private IEnumerator FadeThenLoadGameplayScene()
|
||||
{
|
||||
fadeGroup.gameObject.SetActive(true);
|
||||
fadeGroup.blocksRaycasts = true;
|
||||
fadeGroup.interactable = true;
|
||||
|
||||
float startingAlpha = fadeGroup.alpha;
|
||||
float elapsed = 0f;
|
||||
|
||||
while (elapsed < fadeDuration)
|
||||
{
|
||||
elapsed += Time.unscaledDeltaTime;
|
||||
|
||||
float normalizedTime = Mathf.Clamp01(elapsed / fadeDuration);
|
||||
|
||||
fadeGroup.alpha = Mathf.Lerp(startingAlpha, 1f, normalizedTime);
|
||||
|
||||
yield return null;
|
||||
}
|
||||
|
||||
fadeGroup.alpha = 1f;
|
||||
|
||||
yield return null;
|
||||
|
||||
Debug.Log($"Loading scene: {GameplaySceneName}");
|
||||
|
||||
SceneManager.LoadScene(GameplaySceneName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: afa95fbb3af75b547944ef84e8caddd5
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b13717421ac809d44aaac667dce78981
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
public class DebugFadeToggle : MonoBehaviour
|
||||
{
|
||||
public Image targetImage;
|
||||
public float duration = 0.5f;
|
||||
|
||||
bool isVisible = true;
|
||||
Coroutine running;
|
||||
|
||||
void Start()
|
||||
{
|
||||
var btn = GetComponent<Button>();
|
||||
if (btn != null)
|
||||
btn.onClick.AddListener(ToggleFade);
|
||||
}
|
||||
|
||||
public void ToggleFade()
|
||||
{
|
||||
if (targetImage == null) return;
|
||||
|
||||
float targetAlpha = isVisible ? 0f : 1f;
|
||||
if (running != null) StopCoroutine(running);
|
||||
running = StartCoroutine(FadeTo(targetAlpha));
|
||||
isVisible = !isVisible;
|
||||
}
|
||||
|
||||
IEnumerator FadeTo(float targetAlpha)
|
||||
{
|
||||
float start = targetImage.color.a;
|
||||
float t = 0f;
|
||||
|
||||
while (t < duration)
|
||||
{
|
||||
t += Time.deltaTime;
|
||||
float a = Mathf.Lerp(start, targetAlpha, Mathf.Clamp01(t / duration));
|
||||
var c = targetImage.color;
|
||||
c.a = a;
|
||||
targetImage.color = c;
|
||||
yield return null;
|
||||
}
|
||||
|
||||
var final = targetImage.color;
|
||||
final.a = targetAlpha;
|
||||
targetImage.color = final;
|
||||
running = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e99816cb33c22f840bae5c4d5be9523f
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace ProceduralEditor
|
||||
{
|
||||
// Runtime helper that toggles the alpha of a target Image when the Button it's attached to is clicked.
|
||||
public class DebugFadeToggleBridge : MonoBehaviour
|
||||
{
|
||||
public Image targetImage;
|
||||
public float duration = 0.1f;
|
||||
|
||||
bool isVisible = true;
|
||||
Coroutine running;
|
||||
|
||||
void Start()
|
||||
{
|
||||
var btn = GetComponent<Button>();
|
||||
if (btn != null)
|
||||
btn.onClick.AddListener(ToggleFade);
|
||||
}
|
||||
|
||||
public void ToggleFade()
|
||||
{
|
||||
if (targetImage == null) return;
|
||||
|
||||
float targetAlpha = isVisible ? 0f : 1f;
|
||||
if (running != null) StopCoroutine(running);
|
||||
running = StartCoroutine(FadeTo(targetAlpha));
|
||||
isVisible = !isVisible;
|
||||
}
|
||||
|
||||
IEnumerator FadeTo(float targetAlpha)
|
||||
{
|
||||
float start = targetImage.color.a;
|
||||
float t = 0f;
|
||||
|
||||
while (t < duration)
|
||||
{
|
||||
t += Time.deltaTime;
|
||||
float a = Mathf.Lerp(start, targetAlpha, Mathf.Clamp01(t / duration));
|
||||
var c = targetImage.color;
|
||||
c.a = a;
|
||||
targetImage.color = c;
|
||||
yield return null;
|
||||
}
|
||||
|
||||
var final = targetImage.color;
|
||||
final.a = targetAlpha;
|
||||
targetImage.color = final;
|
||||
running = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 94f21b7480673b540bd619ed7bb266f9
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CanvasGroup))]
|
||||
public class MenuFadeIn : MonoBehaviour
|
||||
{
|
||||
public float delay = 0.3f;
|
||||
public float duration = 3.5f;
|
||||
|
||||
CanvasGroup _group;
|
||||
Coroutine _fadeRoutine;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
// Ensure a CanvasGroup exists (SetupMainMenuScene adds one, but be defensive)
|
||||
_group = GetComponent<CanvasGroup>();
|
||||
if (_group == null) _group = gameObject.AddComponent<CanvasGroup>();
|
||||
|
||||
_group.alpha = 1f;
|
||||
_group.blocksRaycasts = true;
|
||||
Debug.Log("[MenuFadeIn] Awake - CanvasGroup ensured, alpha=1");
|
||||
}
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
// Reset state whenever enabled and start the fade
|
||||
if (_group == null) _group = GetComponent<CanvasGroup>() ?? gameObject.AddComponent<CanvasGroup>();
|
||||
_group.alpha = 1f;
|
||||
_group.blocksRaycasts = true;
|
||||
|
||||
if (_fadeRoutine != null) StopCoroutine(_fadeRoutine);
|
||||
_fadeRoutine = StartCoroutine(Fade());
|
||||
Debug.Log("[MenuFadeIn] OnEnable - starting fade (delay=" + delay + ", duration=" + duration + ")");
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
if (_fadeRoutine != null)
|
||||
{
|
||||
StopCoroutine(_fadeRoutine);
|
||||
_fadeRoutine = null;
|
||||
Debug.Log("[MenuFadeIn] OnDisable - stopped fade coroutine");
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator Fade()
|
||||
{
|
||||
if (delay > 0f) yield return new WaitForSecondsRealtime(delay);
|
||||
|
||||
float t = 0f;
|
||||
while (t < duration)
|
||||
{
|
||||
t += Time.unscaledDeltaTime;
|
||||
_group.alpha = 1f - Mathf.Clamp01(t / duration);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
_group.alpha = 0f;
|
||||
_group.blocksRaycasts = false;
|
||||
Debug.Log("[MenuFadeIn] Fade finished - disabling GameObject");
|
||||
gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dcac9b4ec2e8fe143ac611df7f4b548f
|
||||
Reference in New Issue
Block a user