Import assets from store

This commit is contained in:
Sahik committed 2026-09-23 09:30:04 +08:00
1 parent a05f2e47a2
commit 376e52e323
875 files changed
+128037

No files matched your search

@@ -0,0 +1,238 @@
using UnityEngine;
using UnityEngine.InputSystem;
namespace CharacterMovement
{
[RequireComponent(typeof(Camera))]
/// <summary>
/// A simple follow camera for testing the character controller and running the demo scene.
/// </summary>
/// <remarks>
/// Deliberately not a gameplay camera framework. Its only contract with the motor is calling
/// <see cref="PlayerController.SetMainCameraTransform"/> so movement becomes camera-relative,
/// which means any camera — your own, Cinemachine, or an add-on's — can replace it.
/// </remarks>
public class CameraFollow : MonoBehaviour
{
[Header("Target")]
[SerializeField] private Transform target;
[Tooltip("If Target is not assigned, search this component's scene for one PlayerController at startup. Assign Target explicitly for production, split-screen, additive scenes, or multiplayer.")]
[SerializeField] private bool autoFindTargetInScene = true;
[SerializeField] private Vector3 pivotOffset = new Vector3(0f, 1.4f, 0f);
[Tooltip("Lateral camera offset in local space (positive X = over right shoulder).")]
[SerializeField] private Vector3 shoulderOffset = new Vector3(0.35f, 0f, 0f);
[Header("Distance & Follow")]
[Tooltip("How far the camera sits behind the pivot, in metres.")]
[SerializeField, Min(0.1f)] private float distance = 5f;
[Tooltip("How quickly the camera catches up to the target. Higher is tighter.")]
[SerializeField, Min(1f)] private float followSpeed = 12f;
[Header("Look - Mouse")]
[Tooltip("Degrees of rotation per unit of mouse delta.")]
[SerializeField, Min(0f)] private float mouseSensitivity = 0.15f;
[Tooltip("Caps mouse delta per frame so a hitch cannot whip the camera around.")]
[SerializeField, Min(0f)] private float maxMouseDeltaPerFrame = 120f;
[Header("Look - Gamepad")]
[Tooltip("Degrees per second at full stick deflection.")]
[SerializeField, Min(0f)] private float gamepadSensitivity = 180f;
[Tooltip("Stick movement below this is ignored.")]
[SerializeField, Range(0f, 0.5f)] private float gamepadDeadzone = 0.15f;
[Header("Look - Clamp")]
[Tooltip("Lowest pitch angle in degrees. Negative looks down at the character.")]
[SerializeField] private float minPitch = -20f;
[Tooltip("Highest pitch angle in degrees.")]
[SerializeField] private float maxPitch = 60f;
[Tooltip("Pitch the camera starts at.")]
[SerializeField] private float initialPitch = 20f;
[Tooltip("Inverts vertical look input.")]
[SerializeField] private bool invertY;
[Header("Collision")]
[SerializeField] private bool enableCollision = true;
[SerializeField] private LayerMask collisionMask = ~0;
[SerializeField, Min(0.05f)] private float collisionRadius = 0.3f;
[Tooltip("How fast the camera retracts when blocked (units/sec).")]
[SerializeField, Min(1f)] private float retractSpeed = 30f;
[Tooltip("How fast the camera extends back out after a block clears (units/sec).")]
[SerializeField, Min(0.1f)] private float extendSpeed = 4f;
[Header("Soft Lock-On")]
[SerializeField] private bool enableLockOn = true;
[Tooltip("0 = ignore the lock target, 1 = full yaw alignment toward target.")]
[SerializeField, Range(0f, 1f)] private float lockOnInfluence = 0.65f;
[SerializeField, Min(0.1f)] private float lockOnLerpSpeed = 6f;
[Tooltip("Optional pitch bias when locked on (degrees).")]
[SerializeField, Range(-30f, 30f)] private float lockOnPitchBias = 8f;
[Header("Auto Follow")]
[Tooltip("Drift camera yaw behind the player when moving and the user is idle on look input.")]
[SerializeField, Range(0f, 4f)] private float autoFollowYawSpeed = 1.2f;
[Tooltip("Seconds after last look input before auto-follow kicks in.")]
[SerializeField, Min(0f)] private float autoFollowIdleTime = 0.6f;
public Transform LockOnTarget { get; set; }
private Camera _camera;
private float _yaw;
private float _pitch;
private float _currentDistance;
private Vector3 _followVelocity;
private float _idleTimer;
private void Awake()
{
_camera = GetComponent<Camera>();
}
private void Start()
{
if (!target && autoFindTargetInScene)
{
PlayerController player = SceneReferenceResolver.FindComponentInSameScene<PlayerController>(this);
if (player)
target = player.transform;
}
if (target && target.TryGetComponent(out PlayerController controller))
controller.SetMainCameraTransform(transform);
Vector3 euler = transform.eulerAngles;
_yaw = euler.y;
_pitch = initialPitch;
_currentDistance = distance;
}
private void LateUpdate()
{
if (!target)
return;
Vector2 lookDelta = ReadLookInput(out bool gamepadActive);
ApplyLook(lookDelta, gamepadActive);
ApplyAutoFollow(lookDelta.sqrMagnitude);
ApplyLockOn();
Quaternion rotation = Quaternion.Euler(_pitch, _yaw, 0f);
Vector3 pivot = target.position + pivotOffset;
Vector3 lateral = rotation * shoulderOffset;
Vector3 cameraDirection = -(rotation * Vector3.forward);
float targetDistance = ResolveCollisionDistance(pivot + lateral, cameraDirection);
if (targetDistance < _currentDistance)
_currentDistance = Mathf.MoveTowards(_currentDistance, targetDistance, retractSpeed * Time.deltaTime);
else
_currentDistance = Mathf.MoveTowards(_currentDistance, targetDistance, extendSpeed * Time.deltaTime);
Vector3 desiredPosition = pivot + lateral + cameraDirection * _currentDistance;
Vector3 smoothedPosition = Vector3.SmoothDamp(
transform.position,
desiredPosition,
ref _followVelocity,
1f / followSpeed);
transform.SetPositionAndRotation(smoothedPosition, rotation);
}
private Vector2 ReadLookInput(out bool gamepadActive)
{
gamepadActive = false;
Vector2 result = Vector2.zero;
Mouse mouse = Mouse.current;
if (mouse != null)
{
Vector2 mouseDelta = mouse.delta.ReadValue();
if (maxMouseDeltaPerFrame > 0f)
mouseDelta = Vector2.ClampMagnitude(mouseDelta, maxMouseDeltaPerFrame);
result = mouseDelta * mouseSensitivity;
}
Gamepad gamepad = Gamepad.current;
if (gamepad != null)
{
Vector2 stick = gamepad.rightStick.ReadValue();
if (stick.sqrMagnitude > gamepadDeadzone * gamepadDeadzone)
{
Vector2 stickDelta = stick * (gamepadSensitivity * Time.deltaTime);
if (stickDelta.sqrMagnitude > result.sqrMagnitude)
{
result = stickDelta;
gamepadActive = true;
}
else if (result.sqrMagnitude < 0.001f)
{
result = stickDelta;
gamepadActive = true;
}
}
}
return result;
}
private void ApplyLook(Vector2 lookDelta, bool gamepadActive)
{
float yawDelta = lookDelta.x;
float pitchDelta = invertY ? lookDelta.y : -lookDelta.y;
_yaw += yawDelta;
_pitch = Mathf.Clamp(_pitch + pitchDelta, minPitch, maxPitch);
_idleTimer = lookDelta.sqrMagnitude > 0.0001f ? 0f : _idleTimer + Time.deltaTime;
}
private void ApplyAutoFollow(float lookDeltaSqr)
{
if (autoFollowYawSpeed <= 0f)
return;
if (_idleTimer < autoFollowIdleTime)
return;
if (!target.TryGetComponent(out PlayerController controller) || controller.RigidBody == null)
return;
Vector3 velocity = controller.RigidBody.linearVelocity;
velocity.y = 0f;
if (velocity.sqrMagnitude < 0.5f)
return;
float targetYaw = Mathf.Atan2(velocity.x, velocity.z) * Mathf.Rad2Deg;
_yaw = Mathf.LerpAngle(_yaw, targetYaw, autoFollowYawSpeed * Time.deltaTime);
}
private void ApplyLockOn()
{
if (!enableLockOn || lockOnInfluence <= 0f || LockOnTarget == null)
return;
Vector3 toTarget = LockOnTarget.position - (target.position + pivotOffset);
toTarget.y = 0f;
if (toTarget.sqrMagnitude < 0.0001f)
return;
float yawToTarget = Mathf.Atan2(toTarget.x, toTarget.z) * Mathf.Rad2Deg;
float blend = lockOnInfluence * lockOnLerpSpeed * Time.deltaTime;
_yaw = Mathf.LerpAngle(_yaw, yawToTarget, blend);
if (Mathf.Abs(lockOnPitchBias) > 0.01f)
_pitch = Mathf.LerpAngle(_pitch, lockOnPitchBias, blend);
}
private float ResolveCollisionDistance(Vector3 castOrigin, Vector3 castDirection)
{
if (!enableCollision)
return distance;
if (Physics.SphereCast(castOrigin, collisionRadius, castDirection, out RaycastHit hit, distance, collisionMask, QueryTriggerInteraction.Ignore))
return Mathf.Max(hit.distance, collisionRadius);
return distance;
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 0a01ac3d63e1c814695b6ae5d9680448
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/Camera/CameraFollow.cs
uploadId: 997018
@@ -0,0 +1,238 @@
using System;
using System.Reflection;
using UnityEngine;
namespace CharacterMovement
{
[AddComponentMenu("Character Controller/Camera/Cinemachine Adapter")]
public sealed class CharacterCinemachineAdapter : MonoBehaviour
{
[Header("References")]
[Tooltip("Controller the rig follows. Found automatically when Auto Find Player is on.")]
[SerializeField] private PlayerController playerController;
[Tooltip("Your Cinemachine camera component. Stored as a plain Component so Core compiles without "
+ "Cinemachine installed.")]
[SerializeField] private Component cinemachineCamera;
[Tooltip("Transform the Cinemachine camera follows.")]
[SerializeField] private Transform followTarget;
[Tooltip("Transform the Cinemachine camera looks at.")]
[SerializeField] private Transform lookAtTarget;
[Header("Setup")]
[Tooltip("Searches this scene for a PlayerController when none is assigned.")]
[SerializeField] private bool autoFindPlayer = true;
[Tooltip("Searches this GameObject and its children for a Cinemachine camera.")]
[SerializeField] private bool autoFindCinemachineCamera = true;
[Tooltip("Writes the follow target onto the Cinemachine camera at startup.")]
[SerializeField] private bool assignFollowTarget = true;
[Tooltip("Writes the look-at target onto the Cinemachine camera at startup.")]
[SerializeField] private bool assignLookAtTarget = true;
[Tooltip("Tells the controller to treat this camera as the movement reference, so input stays "
+ "camera-relative. Keep this on.")]
[SerializeField] private bool assignPlayerCameraReference = true;
[Tooltip("How often to re-assign the camera reference, in seconds, in case the Cinemachine brain "
+ "swaps cameras.")]
[SerializeField, Min(0f)] private float cameraReferenceRefreshInterval = 0.25f;
private Camera _cachedMainCamera;
private Transform _lastAssignedCameraTransform;
private float _nextCameraReferenceRefreshTime;
public PlayerController PlayerController => playerController;
public Component CinemachineCamera => cinemachineCamera;
public bool ValidateTargetBindings(out string message)
{
Component resolvedCamera = cinemachineCamera ? cinemachineCamera : autoFindCinemachineCamera ? FindCinemachineComponent() : null;
if (!resolvedCamera)
{
message = "No Cinemachine camera component is assigned or discoverable on this adapter GameObject.";
return false;
}
if (assignFollowTarget && !CanSetTransformMember(resolvedCamera, "Follow", "m_Follow"))
{
message = $"'{resolvedCamera.GetType().Name}' does not expose a writable Follow target member supported by the adapter.";
return false;
}
if (assignLookAtTarget && !CanSetTransformMember(resolvedCamera, "LookAt", "m_LookAt"))
{
message = $"'{resolvedCamera.GetType().Name}' does not expose a writable LookAt target member supported by the adapter.";
return false;
}
message = "Cinemachine target bindings are supported.";
return true;
}
private void Reset()
{
ResolveReferences();
}
private void OnEnable()
{
ResolveReferences();
ApplyTargets();
ApplyPlayerCameraReference();
}
private void LateUpdate()
{
if (cameraReferenceRefreshInterval > 0f
&& Time.unscaledTime < _nextCameraReferenceRefreshTime
&& _lastAssignedCameraTransform)
{
return;
}
ApplyPlayerCameraReference();
}
public bool ApplyTargets()
{
if (!cinemachineCamera)
return false;
Transform resolvedFollow = followTarget ? followTarget : playerController ? playerController.transform : null;
Transform resolvedLookAt = lookAtTarget ? lookAtTarget : resolvedFollow;
bool changed = false;
if (assignFollowTarget && resolvedFollow)
changed |= TrySetTransformMember(cinemachineCamera, "Follow", "m_Follow", resolvedFollow);
if (assignLookAtTarget && resolvedLookAt)
changed |= TrySetTransformMember(cinemachineCamera, "LookAt", "m_LookAt", resolvedLookAt);
return changed;
}
private void ResolveReferences()
{
if (!playerController && autoFindPlayer)
playerController = GetComponentInParent<PlayerController>() ?? SceneReferenceResolver.FindComponentInSameScene<PlayerController>(this);
if (!followTarget && playerController)
followTarget = playerController.transform;
if (!lookAtTarget)
lookAtTarget = followTarget;
if (!cinemachineCamera && autoFindCinemachineCamera)
cinemachineCamera = FindCinemachineComponent();
}
private void ApplyPlayerCameraReference()
{
if (!assignPlayerCameraReference || !playerController)
return;
_nextCameraReferenceRefreshTime = Time.unscaledTime + cameraReferenceRefreshInterval;
Camera mainCamera = ResolveMainCamera();
if (!mainCamera)
return;
Transform cameraTransform = mainCamera.transform;
if (_lastAssignedCameraTransform == cameraTransform)
return;
playerController.SetMainCameraTransform(cameraTransform);
_lastAssignedCameraTransform = cameraTransform;
}
private Camera ResolveMainCamera()
{
if (_cachedMainCamera)
return _cachedMainCamera;
_cachedMainCamera = SceneReferenceResolver.FindMainCameraInSameScene(this);
return _cachedMainCamera;
}
private Component FindCinemachineComponent()
{
Component[] components = GetComponents<Component>();
foreach (Component component in components)
{
if (component != this && IsCinemachineComponent(component))
return component;
}
Component[] children = GetComponentsInChildren<Component>(true);
foreach (Component component in children)
{
if (component != this && IsCinemachineComponent(component))
return component;
}
return null;
}
private static bool IsCinemachineComponent(Component component)
{
if (!component)
return false;
Type type = component.GetType();
string fullName = type.FullName ?? string.Empty;
return fullName.StartsWith("Cinemachine.", StringComparison.Ordinal)
|| type.Name.IndexOf("Cinemachine", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static bool TrySetTransformMember(Component component, string propertyName, string fieldName, Transform value)
{
if (TryGetWritableTransformProperty(component, propertyName, out PropertyInfo property))
{
if (property.GetValue(component) as Transform == value)
return false;
property.SetValue(component, value);
return true;
}
if (TryGetWritableTransformField(component, fieldName, propertyName, out FieldInfo field))
{
if (field.GetValue(component) as Transform == value)
return false;
field.SetValue(component, value);
return true;
}
return false;
}
private static bool CanSetTransformMember(Component component, string propertyName, string fieldName)
{
return TryGetWritableTransformProperty(component, propertyName, out _)
|| TryGetWritableTransformField(component, fieldName, propertyName, out _);
}
private static bool TryGetWritableTransformProperty(Component component, string propertyName, out PropertyInfo property)
{
property = null;
if (!component)
return false;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
property = component.GetType().GetProperty(propertyName, flags);
return property != null
&& property.CanWrite
&& property.PropertyType.IsAssignableFrom(typeof(Transform));
}
private static bool TryGetWritableTransformField(Component component, string fieldName, string fallbackFieldName, out FieldInfo field)
{
field = null;
if (!component)
return false;
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type type = component.GetType();
field = type.GetField(fieldName, flags) ?? type.GetField(fallbackFieldName, flags);
return field != null
&& field.FieldType.IsAssignableFrom(typeof(Transform));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 172c34e7d0ec406fa55c4acd42efde70
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Scripts/Camera/CharacterCinemachineAdapter.cs
uploadId: 997018