Add first-person player at the north-east lake; stop water floating

- PlayerController: 1.83 m (6 ft) CharacterController player with WASD,
  mouse look, Space to jump (buffered, coyote time), Shift to sprint and
  Ctrl held to crouch (stays down under low ceilings); bindings editable
  in the Inspector
- FloatingOrigin: shifts the world back under the player in Play mode so
  the 750 km world doesn't jitter far from the origin
- Player prefab placed on the shore of the north-east lake at the foot of
  the range, facing the lake; old top-down camera kept as a disabled
  "Overview Camera" that BuildFinish frames by name
- Water meshes: river water at most 4 m above the ground, dropping below
  it on steep slopes, and never above a lake's own level near lakes;
  add a menu item to rebuild just the water surfaces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Netherwarlord
2026-11-24 17:06:51 -05:00
co-authored by Claude Opus 5.5
parent 75c196cc00
commit 8579ec537f
58 changed files with 3550 additions and 2640 deletions
+2583 -2525
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a1fdf132b67b31e9f9f8b6a2cb85c194
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,55 @@
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace TravelersQuest.Player
{
/// <summary>
/// Keeps the player near the world origin at runtime. The Bowl Valley world is 750 km across, and far from
/// the origin, float precision makes the camera and physics jitter. Whenever the player gets more than
/// <see cref="threshold"/> metres from the origin, every root object in the loaded scenes is shifted back
/// horizontally. Only Play mode is affected; the saved scene keeps its real coordinates.
/// </summary>
[DefaultExecutionOrder(1000)] // after movement, before rendering
[DisallowMultipleComponent]
public sealed class FloatingOrigin : MonoBehaviour
{
[Min(100f)] public float threshold = 2000f;
/// <summary>Total horizontal shift applied so far (world units). True position = transform position + this.</summary>
public static double OffsetX { get; private set; }
public static double OffsetZ { get; private set; }
/// <summary>Raised after each shift with the amount everything was moved by (subtracted).</summary>
public static event Action<Vector3> Shifted;
public static Vector3 ToTrueWorld(Vector3 p) => new Vector3((float)(p.x + OffsetX), p.y, (float)(p.z + OffsetZ));
void Awake() { OffsetX = 0; OffsetZ = 0; }
void Start() => Recenter();
void LateUpdate()
{
Vector3 p = transform.position;
if (p.x * p.x + p.z * p.z > threshold * threshold) Recenter();
}
public void Recenter()
{
Vector3 p = transform.position;
var shift = new Vector3(p.x, 0f, p.z);
if (shift.sqrMagnitude < 1e-6f) return;
for (int s = 0; s < SceneManager.sceneCount; s++)
{
var scene = SceneManager.GetSceneAt(s);
if (!scene.isLoaded) continue;
foreach (var go in scene.GetRootGameObjects()) go.transform.position -= shift;
}
if (gameObject.scene.name == "DontDestroyOnLoad") transform.root.position -= shift; // not in a loaded scene's roots
Physics.SyncTransforms();
OffsetX += shift.x; OffsetZ += shift.z;
Shifted?.Invoke(shift);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a89b6249a8ced87939e9ce1eaa3ee9a4
+456
View File
@@ -0,0 +1,456 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &5648306647594575426
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 6393905552424145001}
- component: {fileID: 7178283662133633266}
- component: {fileID: 7489576317738268085}
m_Layer: 2
m_Name: Body
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &6393905552424145001
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5648306647594575426}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0.915, z: 0}
m_LocalScale: {x: 0.6, y: 0.915, z: 0.6}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3290525476379539597}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &7178283662133633266
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5648306647594575426}
m_Mesh: {fileID: 10208, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &7489576317738268085
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5648306647594575426}
m_Enabled: 1
m_CastShadows: 3
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RayTracingAccelStructBuildFlagsOverride: 0
m_RayTracingAccelStructBuildFlags: 1
m_SmallMeshCulling: 1
m_ForceMeshLod: -1
m_MeshLodSelectionBias: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_GlobalIlluminationMeshLod: 0
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_MaskInteraction: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1 &5795832090092451035
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 7989328392886976939}
- component: {fileID: 3766653121011666609}
- component: {fileID: 438492533521644050}
- component: {fileID: 5427042738742035584}
m_Layer: 0
m_Name: Head
m_TagString: MainCamera
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &7989328392886976939
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5795832090092451035}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 1.71, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 3290525476379539597}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!20 &3766653121011666609
Camera:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5795832090092451035}
m_Enabled: 1
serializedVersion: 2
m_ClearFlags: 1
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
m_projectionMatrixMode: 1
m_GateFitMode: 2
m_FOVAxisMode: 0
m_Iso: 200
m_ShutterSpeed: 0.005
m_Aperture: 16
m_FocusDistance: 10
m_FocalLength: 50
m_BladeCount: 5
m_Curvature: {x: 2, y: 11}
m_BarrelClipping: 0.25
m_Anamorphism: 0
m_SensorSize: {x: 36, y: 24}
m_LensShift: {x: 0, y: 0}
m_NormalizedViewPortRect:
serializedVersion: 2
x: 0
y: 0
width: 1
height: 1
near clip plane: 0.1
far clip plane: 150000
field of view: 70
orthographic: 0
orthographic size: 5
m_Depth: 0
m_CullingMask:
serializedVersion: 2
m_Bits: 4294967295
m_RenderingPath: -1
m_TargetTexture: {fileID: 0}
m_TargetDisplay: 0
m_TargetEye: 3
m_HDR: 1
m_AllowMSAA: 1
m_AllowDynamicResolution: 0
m_ForceIntoRT: 0
m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!81 &438492533521644050
AudioListener:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5795832090092451035}
m_Enabled: 1
--- !u!114 &5427042738742035584
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5795832090092451035}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a79441f348de89743a2939f4d699eac1, type: 3}
m_Name:
m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Runtime::UnityEngine.Rendering.Universal.UniversalAdditionalCameraData
m_RenderShadows: 1
m_RequiresDepthTextureOption: 2
m_RequiresOpaqueTextureOption: 2
m_CameraType: 0
m_Cameras: []
m_RendererIndex: -1
m_VolumeLayerMask:
serializedVersion: 2
m_Bits: 1
m_VolumeTrigger: {fileID: 0}
m_VolumeFrameworkUpdateModeOption: 2
m_RenderPostProcessing: 0
m_Antialiasing: 0
m_AntialiasingQuality: 2
m_StopNaN: 0
m_Dithering: 0
m_ClearDepth: 1
m_AllowXRRendering: 1
m_AllowHDROutput: 1
m_UseScreenCoordOverride: 0
m_ScreenSizeOverride: {x: 0, y: 0, z: 0, w: 0}
m_ScreenCoordScaleBias: {x: 0, y: 0, z: 0, w: 0}
m_RequiresDepthTexture: 0
m_RequiresColorTexture: 0
m_TaaSettings:
m_Quality: 3
m_FrameInfluence: 0.1
m_JitterScale: 1
m_MipBias: 0
m_VarianceClampScale: 0.9
m_ContrastAdaptiveSharpening: 0
m_Version: 2
--- !u!1 &5931399433065885087
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 3290525476379539597}
- component: {fileID: 5295443033008769348}
- component: {fileID: 3548918191867539775}
- component: {fileID: 4898053832581568272}
m_Layer: 2
m_Name: Player
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &3290525476379539597
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5931399433065885087}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0.9396926, z: 0, w: 0.34202015}
m_LocalPosition: {x: 224500, y: 2925.4983, z: 68350}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 6393905552424145001}
- {fileID: 7989328392886976939}
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!143 &5295443033008769348
CharacterController:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5931399433065885087}
m_Material: {fileID: 0}
m_IncludeLayers:
serializedVersion: 2
m_Bits: 0
m_ExcludeLayers:
serializedVersion: 2
m_Bits: 0
m_LayerOverridePriority: 0
m_ProvidesContacts: 0
m_Enabled: 1
serializedVersion: 3
m_Height: 1.83
m_Radius: 0.3
m_SlopeLimit: 50
m_StepOffset: 0.4
m_SkinWidth: 0.04
m_MinMoveDistance: 0.001
m_Center: {x: 0, y: 0.915, z: 0}
--- !u!114 &3548918191867539775
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5931399433065885087}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a99e5dbe6d1a4c31bbdb95699ef976b2, type: 3}
m_Name:
m_EditorClassIdentifier: Assembly-CSharp::TravelersQuest.Player.PlayerController
standingHeight: 1.83
crouchHeight: 1.15
radius: 0.3
eyeDepth: 0.12
crouchTransitionSpeed: 6
walkSpeed: 4.5
sprintSpeed: 8
crouchSpeed: 2
groundAcceleration: 40
airAcceleration: 8
jumpHeight: 1.1
gravity: 20
groundSnapDistance: 0.6
cameraPivot: {fileID: 7989328392886976939}
bodyVisual: {fileID: 6393905552424145001}
lookSensitivity: 0.1
maxPitch: 85
move:
m_Name: Move
m_Type: 0
m_ExpectedControlType: Vector2
m_Id: 8ba28d66-efdd-49fd-8ddd-4052f89659f9
m_Processors:
m_Interactions:
m_SingletonActionBindings:
- m_Name: 2DVector
m_Id: c354917d-cf8c-4020-9ce6-f1d68f83b09f
m_Path: 2DVector
m_Interactions:
m_Processors:
m_Groups:
m_Action: Move
m_Flags: 4
- m_Name: Up
m_Id: 7ff77a2e-43c2-44e1-ba9e-d4abd99bcc35
m_Path: <Keyboard>/w
m_Interactions:
m_Processors:
m_Groups:
m_Action: Move
m_Flags: 8
- m_Name: Down
m_Id: 35200702-686d-4563-b47b-ccf63eb9eb9c
m_Path: <Keyboard>/s
m_Interactions:
m_Processors:
m_Groups:
m_Action: Move
m_Flags: 8
- m_Name: Left
m_Id: 6812f508-aa60-4792-b487-715e3d972170
m_Path: <Keyboard>/a
m_Interactions:
m_Processors:
m_Groups:
m_Action: Move
m_Flags: 8
- m_Name: Right
m_Id: 7c8197fc-1532-4b19-8363-0abadb72ff11
m_Path: <Keyboard>/d
m_Interactions:
m_Processors:
m_Groups:
m_Action: Move
m_Flags: 8
m_Flags: 0
m_Priority: 0
look:
m_Name: Look
m_Type: 0
m_ExpectedControlType: Vector2
m_Id: 9996521e-111f-4b9f-842b-dff49bab56fe
m_Processors:
m_Interactions:
m_SingletonActionBindings:
- m_Name:
m_Id: 8069840f-f835-4742-a0e8-00f8dd2a2652
m_Path: <Mouse>/delta
m_Interactions:
m_Processors:
m_Groups:
m_Action: Look
m_Flags: 0
m_Flags: 0
m_Priority: 0
jump:
m_Name: Jump
m_Type: 1
m_ExpectedControlType:
m_Id: f6a5d9e8-a6a6-419e-8ba3-b636044b2596
m_Processors:
m_Interactions:
m_SingletonActionBindings:
- m_Name:
m_Id: 32836c32-9806-4839-ba9d-2b4c6dfff6a3
m_Path: <Keyboard>/space
m_Interactions:
m_Processors:
m_Groups:
m_Action: Jump
m_Flags: 0
m_Flags: 0
m_Priority: 0
sprint:
m_Name: Sprint
m_Type: 1
m_ExpectedControlType:
m_Id: 6a093a86-edd5-42b2-a64c-664cb08f98a6
m_Processors:
m_Interactions:
m_SingletonActionBindings:
- m_Name:
m_Id: 1eb1dc25-c968-4bd3-b0ac-303b950a39f9
m_Path: <Keyboard>/shift
m_Interactions:
m_Processors:
m_Groups:
m_Action: Sprint
m_Flags: 0
m_Flags: 0
m_Priority: 0
crouch:
m_Name: Crouch
m_Type: 1
m_ExpectedControlType:
m_Id: 0099f2be-88e1-41be-a33c-3a6d68c2eb57
m_Processors:
m_Interactions:
m_SingletonActionBindings:
- m_Name:
m_Id: b01d6110-7127-42da-a022-f83e6080876f
m_Path: <Keyboard>/ctrl
m_Interactions:
m_Processors:
m_Groups:
m_Action: Crouch
m_Flags: 0
m_Flags: 0
m_Priority: 0
snapToGroundOnStart: 1
lockCursorOnStart: 1
--- !u!114 &4898053832581568272
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 5931399433065885087}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a89b6249a8ced87939e9ce1eaa3ee9a4, type: 3}
m_Name:
m_EditorClassIdentifier: Assembly-CSharp::TravelersQuest.Player.FloatingOrigin
threshold: 2000
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: fbc5eb59355b9eedf86d31fc182d5941
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,263 @@
using UnityEngine;
using UnityEngine.InputSystem;
namespace TravelersQuest.Player
{
/// <summary>
/// First-person player, about 6 ft (1.83 m) tall.
/// WASD moves, the mouse looks, Space jumps, Shift sprints, and Ctrl crouches while held.
/// Esc frees the cursor; click in the Game view to capture it again.
/// The transform's origin is at the player's feet.
/// </summary>
[RequireComponent(typeof(CharacterController))]
[DisallowMultipleComponent]
public sealed class PlayerController : MonoBehaviour
{
[Header("Body (metres)")]
[Tooltip("Standing height. 6 ft = 1.83 m.")]
[Min(0.5f)] public float standingHeight = 1.83f;
[Min(0.5f)] public float crouchHeight = 1.15f;
[Min(0.1f)] public float radius = 0.3f;
[Tooltip("How far below the top of the head the eyes sit.")]
[Min(0f)] public float eyeDepth = 0.12f;
[Tooltip("Metres per second the body grows or shrinks when crouching or standing.")]
[Min(0.5f)] public float crouchTransitionSpeed = 6f;
[Header("Movement (m/s)")]
[Min(0f)] public float walkSpeed = 4.5f;
[Min(0f)] public float sprintSpeed = 8f;
[Min(0f)] public float crouchSpeed = 2f;
[Min(0f)] public float groundAcceleration = 40f;
[Min(0f)] public float airAcceleration = 8f;
[Tooltip("Height of a standing jump in metres.")]
[Min(0f)] public float jumpHeight = 1.1f;
[Min(0f)] public float gravity = 20f;
[Tooltip("How far the player is pulled down to stay on the ground when walking off bumps or down slopes.")]
[Min(0f)] public float groundSnapDistance = 0.6f;
[Tooltip("A jump pressed this long before landing still happens on landing (seconds).")]
[Min(0f)] public float jumpBufferTime = 0.15f;
[Tooltip("Jumping still works this long after walking off an edge (seconds).")]
[Min(0f)] public float coyoteTime = 0.1f;
[Header("Look")]
[Tooltip("Pitches up and down; normally the player camera.")]
public Transform cameraPivot;
[Tooltip("Optional visible body, scaled with the current height.")]
public Transform bodyVisual;
[Range(0.01f, 1f)] public float lookSensitivity = 0.1f;
[Range(10f, 89f)] public float maxPitch = 85f;
[Header("Input (rebind here in the Inspector)")]
public InputAction move;
public InputAction look;
public InputAction jump;
public InputAction sprint;
public InputAction crouch;
[Header("Start")]
[Tooltip("Drop onto the terrain below the placed position when play starts.")]
public bool snapToGroundOnStart = true;
public bool lockCursorOnStart = true;
public bool IsGrounded { get; private set; }
public bool IsCrouching { get; private set; }
public bool IsSprinting { get; private set; }
public Vector3 Velocity => velocity;
CharacterController body;
Vector3 velocity;
float yaw, pitch;
float jumpPressedAt = float.NegativeInfinity, lastGroundedAt = float.NegativeInfinity;
void OnJumpPressed(InputAction.CallbackContext _) => jumpPressedAt = Time.time;
// Raycasts skip the "Ignore Raycast" layer the player lives on, so they never hit the player's own capsule.
static int WorldMask => Physics.DefaultRaycastLayers;
void Reset() => AssignDefaultBindings(force: true);
void Awake()
{
body = GetComponent<CharacterController>();
AssignDefaultBindings(force: false);
yaw = transform.eulerAngles.y;
if (cameraPivot)
{
pitch = cameraPivot.localEulerAngles.x;
if (pitch > 180f) pitch -= 360f;
}
body.radius = radius;
body.slopeLimit = 50f;
body.stepOffset = 0.4f;
body.skinWidth = 0.04f;
body.minMoveDistance = 0f;
SetHeight(standingHeight);
}
void OnEnable()
{
jump.performed += OnJumpPressed;
move.Enable(); look.Enable(); jump.Enable(); sprint.Enable(); crouch.Enable();
}
void OnDisable()
{
jump.performed -= OnJumpPressed;
move.Disable(); look.Disable(); jump.Disable(); sprint.Disable(); crouch.Disable();
SetCursorLocked(false);
}
void Start()
{
if (snapToGroundOnStart) SnapToGround();
if (lockCursorOnStart) SetCursorLocked(true);
}
void Update()
{
float dt = Time.deltaTime;
if (dt <= 0f) return;
HandleCursor();
if (Cursor.lockState == CursorLockMode.Locked) Look();
UpdateCrouch(dt);
Move(dt);
}
// ---------- input ----------
void AssignDefaultBindings(bool force)
{
if (force || move == null || move.bindings.Count == 0)
{
move = new InputAction("Move", InputActionType.Value, expectedControlType: "Vector2");
move.AddCompositeBinding("2DVector")
.With("Up", "<Keyboard>/w").With("Down", "<Keyboard>/s")
.With("Left", "<Keyboard>/a").With("Right", "<Keyboard>/d");
}
if (force || look == null || look.bindings.Count == 0)
look = new InputAction("Look", InputActionType.Value, "<Mouse>/delta", expectedControlType: "Vector2");
if (force || jump == null || jump.bindings.Count == 0)
jump = new InputAction("Jump", InputActionType.Button, "<Keyboard>/space");
if (force || sprint == null || sprint.bindings.Count == 0)
sprint = new InputAction("Sprint", InputActionType.Button, "<Keyboard>/shift");
if (force || crouch == null || crouch.bindings.Count == 0)
crouch = new InputAction("Crouch", InputActionType.Button, "<Keyboard>/ctrl");
}
static void HandleCursor()
{
var kb = Keyboard.current; var mouse = Mouse.current;
if (kb != null && kb.escapeKey.wasPressedThisFrame) SetCursorLocked(false);
else if (mouse != null && mouse.leftButton.wasPressedThisFrame && Cursor.lockState != CursorLockMode.Locked)
SetCursorLocked(true);
}
static void SetCursorLocked(bool locked)
{
Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !locked;
}
void Look()
{
Vector2 d = look.ReadValue<Vector2>() * lookSensitivity; // mouse delta is per frame already
yaw += d.x;
pitch = Mathf.Clamp(pitch - d.y, -maxPitch, maxPitch);
transform.rotation = Quaternion.Euler(0f, yaw, 0f);
if (cameraPivot) cameraPivot.localRotation = Quaternion.Euler(pitch, 0f, 0f);
}
// ---------- crouch ----------
void UpdateCrouch(float dt)
{
bool want = crouch.IsPressed();
if (!want && IsCrouching && !CanStand()) want = true; // stay down under low ceilings
IsCrouching = want;
float target = IsCrouching ? crouchHeight : standingHeight;
if (!Mathf.Approximately(body.height, target))
SetHeight(Mathf.MoveTowards(body.height, target, crouchTransitionSpeed * dt));
}
bool CanStand()
{
float r = body.radius * 0.95f;
Vector3 top = transform.position + Vector3.up * (body.height - body.radius);
float room = standingHeight - body.height + 0.05f;
return !Physics.SphereCast(top, r, Vector3.up, out _, room, WorldMask, QueryTriggerInteraction.Ignore);
}
void SetHeight(float h)
{
body.height = h;
body.center = new Vector3(0f, h * 0.5f, 0f);
if (cameraPivot) cameraPivot.localPosition = new Vector3(0f, h - eyeDepth, 0f);
if (bodyVisual)
{
bodyVisual.localPosition = new Vector3(0f, h * 0.5f, 0f);
bodyVisual.localScale = new Vector3(radius * 2f, h * 0.5f, radius * 2f); // Unity capsule mesh: 2 tall, 1 wide
}
}
// ---------- movement ----------
void Move(float dt)
{
bool wasGrounded = body.isGrounded;
Vector2 input = Vector2.ClampMagnitude(move.ReadValue<Vector2>(), 1f);
IsSprinting = sprint.IsPressed() && !IsCrouching && input.y > 0.1f;
float speed = IsCrouching ? crouchSpeed : IsSprinting ? sprintSpeed : walkSpeed;
Vector3 wish = (transform.right * input.x + transform.forward * input.y) * speed;
Vector3 horizontal = Vector3.MoveTowards(new Vector3(velocity.x, 0f, velocity.z), wish,
(wasGrounded ? groundAcceleration : airAcceleration) * dt);
float vy = velocity.y;
bool jumped = false;
if (wasGrounded)
{
lastGroundedAt = Time.time;
if (vy < 0f) vy = -2f; // keep pressed onto the ground
}
bool canJump = wasGrounded || (Time.time - lastGroundedAt <= coyoteTime && vy <= 0f);
if (canJump && Time.time - jumpPressedAt <= jumpBufferTime)
{
vy = Mathf.Sqrt(2f * gravity * jumpHeight);
jumped = true;
jumpPressedAt = float.NegativeInfinity;
lastGroundedAt = float.NegativeInfinity;
}
vy -= gravity * dt;
velocity = new Vector3(horizontal.x, vy, horizontal.z);
var flags = body.Move(velocity * dt);
if ((flags & CollisionFlags.Above) != 0 && velocity.y > 0f) velocity.y = 0f;
// Walking off a bump or down a slope: stick to the ground instead of hopping.
if (wasGrounded && !jumped && !body.isGrounded && velocity.y <= 0f) StickToGround();
IsGrounded = body.isGrounded;
if (IsGrounded && velocity.y < 0f) velocity.y = -2f;
}
void StickToGround()
{
float r = body.radius * 0.95f;
Vector3 origin = transform.position + Vector3.up * body.radius;
if (Physics.SphereCast(origin, r, Vector3.down, out var hit, groundSnapDistance + body.skinWidth, WorldMask, QueryTriggerInteraction.Ignore)
&& Vector3.Angle(hit.normal, Vector3.up) <= body.slopeLimit)
body.Move(Vector3.down * hit.distance);
}
/// <summary>Places the player's feet on the ground directly below (or above) its current position.</summary>
public void SnapToGround()
{
Vector3 p = transform.position;
if (!Physics.Raycast(p + Vector3.up * 5000f, Vector3.down, out var hit, 20000f, WorldMask, QueryTriggerInteraction.Ignore)) return;
body.enabled = false;
transform.position = hit.point + Vector3.up * 0.05f;
body.enabled = true;
velocity = Vector3.zero;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a99e5dbe6d1a4c31bbdb95699ef976b2
@@ -18,6 +18,7 @@ namespace TravelersQuest.World.Editor
public const string ReferencePath = "Assets/Bowl Valley Terrain Reference Sheet.png"; public const string ReferencePath = "Assets/Bowl Valley Terrain Reference Sheet.png";
public const string OutputFolder = "Assets/TravelersQuest/World/Terrains/BowlValley_500km"; public const string OutputFolder = "Assets/TravelersQuest/World/Terrains/BowlValley_500km";
public const string RootName = "Bowl Valley Terrain - 500 km"; public const string RootName = "Bowl Valley Terrain - 500 km";
public const string OverviewCameraName = "Overview Camera";
// SizeX/SizeZ: the reference map's frame (the original 500 x 368 km continent core). // SizeX/SizeZ: the reference map's frame (the original 500 x 368 km continent core).
public const float SizeX = 500000f, SizeZ = 368000f, MaxHeight = 3300f; public const float SizeX = 500000f, SizeZ = 368000f, MaxHeight = 3300f;
// The world adds two tiles of new coastal land + sea on every side; the tile lattice matches the original 8x6 // The world adds two tiles of new coastal land + sea on every side; the tile lattice matches the original 8x6
@@ -647,6 +648,8 @@ namespace TravelersQuest.World.Editor
static Material OceanMaterial() => WaterMaterial(OutputFolder + "/Ocean.mat", static Material OceanMaterial() => WaterMaterial(OutputFolder + "/Ocean.mat",
new Color(0.10f, 0.50f, 0.56f), new Color(0.02f, 0.09f, 0.22f), 0.012f, 30f, 8f, 9000f); new Color(0.10f, 0.50f, 0.56f), new Color(0.02f, 0.09f, 0.22f), 0.012f, 30f, 8f, 9000f);
const float RiverMaxDepth = 4f; // true metres of river water above the local ground
// Surface mesh over the rivers and lakes of one tile (every 2nd heightmap sample, ~122 m). // Surface mesh over the rivers and lakes of one tile (every 2nd heightmap sample, ~122 m).
static Mesh BuildWaterMesh(float[] hm, int res, double ox, double oz, float tileW, float tileD) static Mesh BuildWaterMesh(float[] hm, int res, double ox, double oz, float tileW, float tileD)
{ {
@@ -664,6 +667,27 @@ namespace TravelersQuest.World.Editor
ExtWater(wx, wz, out float extL, out float extC); ExtWater(wx, wz, out float extL, out float extC);
lvl[k] = extC > 0.05f ? (coreL > -5000 && coreW > 0.05f ? Mathf.Min(extL, coreL) : extL) : coreL; lvl[k] = extC > 0.05f ? (coreL > -5000 && coreW > 0.05f ? Mathf.Min(extL, coreL) : extL) : coreL;
wet[k] = (coreW > 0.2f && coreL > -5000) || extC > 0.3f; wet[k] = (coreW > 0.2f && coreL > -5000) || extC > 0.3f;
if (lvl[k] > -5000)
{
// River levels are smoothed over ~1 km, so on steep reaches they overshoot the ground below.
// Keep river water at most RiverMaxDepth above the terrain; lakes stay flat at their level.
// On steep ground (as seen at the exaggerated scale) the river slips under the terrain,
// so cascades read as dry gullies instead of water draped over a cliff.
int hi = Mathf.Clamp(i * step, 1, res - 2), hj = Mathf.Clamp(j * step, 1, res - 2);
float cell = tileW / (res - 1);
float gx = (hm[hj * res + hi + 1] - hm[hj * res + hi - 1]) / (2 * cell);
float gz = (hm[(hj + 1) * res + hi] - hm[(hj - 1) * res + hi]) / (2 * cell);
float steep = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.35f, 0.7f, Mathf.Sqrt(gx * gx + gz * gz) * VerticalExaggeration));
float depth = Mathf.Lerp(RiverMaxDepth, -1.5f, steep);
// Near a lake the surface never rises above the lake's own flat level unless the ground does.
float ceiling = terr[k] + depth;
if (SampleField(fields.lakeW, (float)wx, (float)wz) > 0.01f)
ceiling = Mathf.Max(ceiling, SampleField(fields.lakeLevel, (float)wx, (float)wz));
lvl[k] = Mathf.Min(lvl[k], ceiling);
// Vertices outside the wet area only exist to close a quad: tuck them under the ground so the
// mesh edge never hangs in the air.
if (!wet[k]) lvl[k] = Mathf.Min(lvl[k], terr[k] - 1);
}
} }
}); });
var verts = new List<Vector3>(); var tris = new List<int>(); var map = new Dictionary<int, int>(); var verts = new List<Vector3>(); var tris = new List<int>(); var map = new Dictionary<int, int>();
@@ -1138,32 +1162,65 @@ namespace TravelersQuest.World.Editor
if (!anySolid) go.SetActive(false); // tile lies wholly outside the outline if (!anySolid) go.SetActive(false); // tile lies wholly outside the outline
sb.Append(go.name).Append(anySolid ? " " : "(empty) "); sb.Append(go.name).Append(anySolid ? " " : "(empty) ");
if (!CutOutsideOutline) if (!CutOutsideOutline) AddWaterSurface(root.transform, hm, res, tx, tz);
{
var wm = BuildWaterMesh(hm, res, ox, oz, tileW, tileD);
if (wm != null)
{
EnsureFolder(OutputFolder + "/Water");
string mp = $"{OutputFolder}/Water/Water_{tx:D2}_{tz:D2}.asset";
AssetDatabase.CreateAsset(wm, mp);
var waterRoot = root.transform.Find("Rivers & Lakes") ?? new GameObject("Rivers & Lakes").transform;
waterRoot.SetParent(root.transform, false);
var w = new GameObject($"Water {tx:D2}-{tz:D2}", typeof(MeshFilter), typeof(MeshRenderer));
w.transform.SetParent(waterRoot, false);
w.transform.position = new Vector3((float)ox, 0, (float)oz);
w.GetComponent<MeshFilter>().sharedMesh = wm;
var mr = w.GetComponent<MeshRenderer>();
mr.sharedMaterial = FreshwaterMaterial();
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
}
}
} }
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(root.scene); UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(root.scene);
AssetDatabase.SaveAssets(); AssetDatabase.SaveAssets();
return sb.ToString(); return sb.ToString();
} }
static void AddWaterSurface(Transform root, float[] hm, int res, int tx, int tz)
{
double ox = -WorldSizeX / 2 + tx * TileW, oz = -WorldSizeZ / 2 + tz * TileD;
var wm = BuildWaterMesh(hm, res, ox, oz, TileW, TileD);
if (wm == null) return;
EnsureFolder(OutputFolder + "/Water");
string mp = $"{OutputFolder}/Water/Water_{tx:D2}_{tz:D2}.asset";
AssetDatabase.CreateAsset(wm, mp);
var waterRoot = root.Find("Rivers & Lakes") ?? new GameObject("Rivers & Lakes").transform;
waterRoot.SetParent(root, false);
var w = new GameObject($"Water {tx:D2}-{tz:D2}", typeof(MeshFilter), typeof(MeshRenderer));
w.transform.SetParent(waterRoot, false);
w.transform.position = new Vector3((float)ox, 0, (float)oz);
w.GetComponent<MeshFilter>().sharedMesh = wm;
var mr = w.GetComponent<MeshRenderer>();
mr.sharedMaterial = FreshwaterMaterial();
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
}
// Regenerates only the river/lake surface meshes from the terrain tiles already in the scene (no terrain rebuild).
[MenuItem("Travelers Quest/Rebuild Bowl Valley Water Surfaces")]
public static void RebuildWaterSurfacesFromMenu() => UnityEngine.Debug.Log(RebuildWaterSurfaces());
public static string RebuildWaterSurfaces()
{
if (fields == null) Prepare();
var root = GameObject.Find(RootName);
if (!root) return "No terrain root in the open scene.";
var old = root.transform.Find("Rivers & Lakes");
if (old) UnityEngine.Object.DestroyImmediate(old.gameObject);
foreach (var guid in AssetDatabase.FindAssets("t:Mesh", new[] { OutputFolder + "/Water" }))
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(guid));
float rangeY = MaxHeight + SeaDepth, baseY = -SeaDepth;
int count = 0;
foreach (var t in root.GetComponentsInChildren<Terrain>(true))
{
var p = t.transform.position;
int tx = Mathf.RoundToInt((p.x + WorldSizeX / 2) / TileW), tz = Mathf.RoundToInt((p.z + WorldSizeZ / 2) / TileD);
var td = t.terrainData; int res = td.heightmapResolution;
var h = td.GetHeights(0, 0, res, res);
var hm = new float[res * res];
for (int j = 0; j < res; j++) for (int i = 0; i < res; i++) hm[j * res + i] = baseY + h[j, i] * rangeY;
AddWaterSurface(root.transform, hm, res, tx, tz);
count++;
}
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(root.scene);
UnityEditor.SceneManagement.EditorSceneManager.SaveScene(root.scene);
AssetDatabase.SaveAssets();
return $"Rebuilt water surfaces over {count} tiles.";
}
// elevation band membership (metres) with soft transitions // elevation band membership (metres) with soft transitions
static void BandWeights(float h, float[] w) static void BandWeights(float h, float[] w)
{ {
@@ -1192,8 +1249,10 @@ namespace TravelersQuest.World.Editor
if (CreateOcean && !CutOutsideOutline) CreateOceanPlane(root.transform); if (CreateOcean && !CutOutsideOutline) CreateOceanPlane(root.transform);
// Camera framing for the whole continent. // Camera framing for the whole continent (the overview camera, never the player's camera).
var cam = Camera.main; var overview = GameObject.Find(OverviewCameraName);
var cam = overview ? overview.GetComponent<Camera>() : Camera.main;
if (cam && cam.GetComponentInParent<CharacterController>()) cam = null;
if (cam) if (cam)
{ {
cam.farClipPlane = 2000000; cam.nearClipPlane = 10; cam.farClipPlane = 2000000; cam.nearClipPlane = 10;