Upload project

This commit is contained in:
Lauchstange committed 2025-01-30 17:20:27 +01:00
1 parent 6bbeab16d1
commit bf545f3baf
371 files changed
+91095

No files matched your search

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d266609e8af72ea41909b7a326478e84
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
using System;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
[Serializable]
public struct CameraTarget : IComponentData
{
public Entity TargetEntity;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 74ff9a59933a5494bbc1bb465a5f2180
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,22 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
[DisallowMultipleComponent]
public class CameraTargetAuthoring : MonoBehaviour
{
public GameObject Target;
public class Baker : Baker<CameraTargetAuthoring>
{
public override void Bake(CameraTargetAuthoring authoring)
{
Entity entity = GetEntity(TransformUsageFlags.Dynamic);
AddComponent(entity, new CameraTarget
{
TargetEntity = GetEntity(authoring.Target, TransformUsageFlags.Dynamic),
});
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d3a88336df575c34e80048c54a815367
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,44 @@
using System;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
[Serializable]
public struct OrbitCamera : IComponentData
{
public float RotationSpeed;
public float MaxVAngle;
public float MinVAngle;
public bool RotateWithCharacterParent;
public float MinDistance;
public float MaxDistance;
public float DistanceMovementSpeed;
public float DistanceMovementSharpness;
public float ObstructionRadius;
public float ObstructionInnerSmoothingSharpness;
public float ObstructionOuterSmoothingSharpness;
public bool PreventFixedUpdateJitter;
public float TargetDistance;
public float SmoothedTargetDistance;
public float ObstructedDistance;
public float PitchAngle;
public float3 PlanarForward;
}
[Serializable]
public struct OrbitCameraControl : IComponentData
{
public Entity FollowedCharacterEntity;
public float2 LookDegreesDelta;
public float ZoomDelta;
}
[Serializable]
public struct OrbitCameraIgnoredEntityBufferElement : IBufferElementData
{
public Entity Entity;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 441900b2dca2cda429cba5f372fcf5fe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,75 @@
using System.Collections.Generic;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
[DisallowMultipleComponent]
public class OrbitCameraAuthoring : MonoBehaviour
{
[Header("Rotation")]
public float RotationSpeed = 2f;
public float MaxVAngle = 89f;
public float MinVAngle = -89f;
public bool RotateWithCharacterParent = true;
[Header("Distance")]
public float StartDistance = 5f;
public float MinDistance = 0f;
public float MaxDistance = 10f;
public float DistanceMovementSpeed = 1f;
public float DistanceMovementSharpness = 20f;
[Header("Obstructions")]
public float ObstructionRadius = 0.1f;
public float ObstructionInnerSmoothingSharpness = float.MaxValue;
public float ObstructionOuterSmoothingSharpness = 5f;
public bool PreventFixedUpdateJitter = true;
[Header("Misc")]
public List<GameObject> IgnoredEntities = new List<GameObject>();
public class Baker : Baker<OrbitCameraAuthoring>
{
public override void Bake(OrbitCameraAuthoring authoring)
{
Entity entity = GetEntity(TransformUsageFlags.Dynamic | TransformUsageFlags.WorldSpace);
AddComponent(entity, new OrbitCamera
{
RotationSpeed = authoring.RotationSpeed,
MaxVAngle = authoring.MaxVAngle,
MinVAngle = authoring.MinVAngle,
RotateWithCharacterParent = authoring.RotateWithCharacterParent,
MinDistance = authoring.MinDistance,
MaxDistance = authoring.MaxDistance,
DistanceMovementSpeed = authoring.DistanceMovementSpeed,
DistanceMovementSharpness = authoring.DistanceMovementSharpness,
ObstructionRadius = authoring.ObstructionRadius,
ObstructionInnerSmoothingSharpness = authoring.ObstructionInnerSmoothingSharpness,
ObstructionOuterSmoothingSharpness = authoring.ObstructionOuterSmoothingSharpness,
PreventFixedUpdateJitter = authoring.PreventFixedUpdateJitter,
TargetDistance = authoring.StartDistance,
SmoothedTargetDistance = authoring.StartDistance,
ObstructedDistance = authoring.StartDistance,
PitchAngle = 0f,
PlanarForward = -math.forward(),
});
AddComponent(entity, new OrbitCameraControl());
DynamicBuffer<OrbitCameraIgnoredEntityBufferElement> ignoredEntitiesBuffer = AddBuffer<OrbitCameraIgnoredEntityBufferElement>(entity);
for (int i = 0; i < authoring.IgnoredEntities.Count; i++)
{
ignoredEntitiesBuffer.Add(new OrbitCameraIgnoredEntityBufferElement
{
Entity = GetEntity(authoring.IgnoredEntities[i], TransformUsageFlags.None),
});
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 70c323b4be4b1fa4089d1a1fd2872754
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,367 @@
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Transforms;
using Unity.CharacterController;
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(ThirdPersonPlayerVariableStepControlSystem))]
[UpdateAfter(typeof(ThirdPersonCharacterVariableUpdateSystem))]
[UpdateBefore(typeof(TransformSystemGroup))]
[BurstCompile]
public partial struct OrbitCameraSimulationSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<OrbitCamera, OrbitCameraControl>().Build());
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
OrbitCameraSimulationJob job = new OrbitCameraSimulationJob
{
DeltaTime = SystemAPI.Time.DeltaTime,
LocalTransformLookup = SystemAPI.GetComponentLookup<LocalTransform>(false),
ParentLookup = SystemAPI.GetComponentLookup<Parent>(true),
PostTransformMatrixLookup = SystemAPI.GetComponentLookup<PostTransformMatrix>(true),
CameraTargetLookup = SystemAPI.GetComponentLookup<CameraTarget>(true),
KinematicCharacterBodyLookup = SystemAPI.GetComponentLookup<KinematicCharacterBody>(true),
};
job.Schedule();
}
[BurstCompile]
[WithAll(typeof(Simulate))]
public partial struct OrbitCameraSimulationJob : IJobEntity
{
public float DeltaTime;
public ComponentLookup<LocalTransform> LocalTransformLookup;
[ReadOnly] public ComponentLookup<Parent> ParentLookup;
[ReadOnly] public ComponentLookup<PostTransformMatrix> PostTransformMatrixLookup;
[ReadOnly] public ComponentLookup<CameraTarget> CameraTargetLookup;
[ReadOnly] public ComponentLookup<KinematicCharacterBody> KinematicCharacterBodyLookup;
void Execute(Entity entity, ref OrbitCamera orbitCamera, in OrbitCameraControl cameraControl)
{
if (OrbitCameraUtilities.TryGetCameraTargetSimulationWorldTransform(
cameraControl.FollowedCharacterEntity,
ref LocalTransformLookup,
ref ParentLookup,
ref PostTransformMatrixLookup,
ref CameraTargetLookup,
out float4x4 targetWorldTransform))
{
float3 targetUp = targetWorldTransform.Up();
float3 targetPosition = targetWorldTransform.Translation();
// Update planar forward based on target up direction and rotation from parent
{
quaternion tmpPlanarRotation = MathUtilities.CreateRotationWithUpPriority(targetUp, orbitCamera.PlanarForward);
// Rotation from character parent
if (orbitCamera.RotateWithCharacterParent &&
KinematicCharacterBodyLookup.TryGetComponent(cameraControl.FollowedCharacterEntity, out KinematicCharacterBody characterBody))
{
// Only consider rotation around the character up, since the camera is already adjusting itself to character up
quaternion planarRotationFromParent = characterBody.RotationFromParent;
KinematicCharacterUtilities.AddVariableRateRotationFromFixedRateRotation(ref tmpPlanarRotation, planarRotationFromParent, DeltaTime, characterBody.LastPhysicsUpdateDeltaTime);
}
orbitCamera.PlanarForward = MathUtilities.GetForwardFromRotation(tmpPlanarRotation);
}
// Yaw
float yawAngleChange = cameraControl.LookDegreesDelta.x * orbitCamera.RotationSpeed;
quaternion yawRotation = quaternion.Euler(targetUp * math.radians(yawAngleChange));
orbitCamera.PlanarForward = math.rotate(yawRotation, orbitCamera.PlanarForward);
// Pitch
orbitCamera.PitchAngle += -cameraControl.LookDegreesDelta.y * orbitCamera.RotationSpeed;
orbitCamera.PitchAngle = math.clamp(orbitCamera.PitchAngle, orbitCamera.MinVAngle, orbitCamera.MaxVAngle);
// Calculate final rotation
quaternion cameraRotation = OrbitCameraUtilities.CalculateCameraRotation(targetUp, orbitCamera.PlanarForward, orbitCamera.PitchAngle);
// Distance input
float desiredDistanceMovementFromInput = cameraControl.ZoomDelta * orbitCamera.DistanceMovementSpeed;
orbitCamera.TargetDistance = math.clamp(orbitCamera.TargetDistance + desiredDistanceMovementFromInput, orbitCamera.MinDistance, orbitCamera.MaxDistance);
// Calculate camera position (no smoothing or obstructions yet; these are done in the camera late update)
float3 cameraPosition = OrbitCameraUtilities.CalculateCameraPosition(targetPosition, cameraRotation, orbitCamera.TargetDistance);
// Write back to component
LocalTransformLookup[entity] = LocalTransform.FromPositionRotation(cameraPosition, cameraRotation);
}
}
}
}
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(TransformSystemGroup))]
[BurstCompile]
public partial struct OrbitCameraLateUpdateSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<PhysicsWorldSingleton>();
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<OrbitCamera, OrbitCameraControl>().Build());
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
OrbitCameraLateUpdateJob job = new OrbitCameraLateUpdateJob
{
DeltaTime = SystemAPI.Time.DeltaTime,
PhysicsWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>().PhysicsWorld,
LocalToWorldLookup = SystemAPI.GetComponentLookup<LocalToWorld>(false),
CameraTargetLookup = SystemAPI.GetComponentLookup<CameraTarget>(true),
KinematicCharacterBodyLookup = SystemAPI.GetComponentLookup<KinematicCharacterBody>(true),
};
job.Schedule();
}
[BurstCompile]
[WithAll(typeof(Simulate))]
public partial struct OrbitCameraLateUpdateJob : IJobEntity
{
public float DeltaTime;
[ReadOnly]
public PhysicsWorld PhysicsWorld;
public ComponentLookup<LocalToWorld> LocalToWorldLookup;
[ReadOnly]
public ComponentLookup<CameraTarget> CameraTargetLookup;
[ReadOnly]
public ComponentLookup<KinematicCharacterBody> KinematicCharacterBodyLookup;
void Execute(
Entity entity,
ref OrbitCamera orbitCamera,
in OrbitCameraControl cameraControl,
in DynamicBuffer<OrbitCameraIgnoredEntityBufferElement> ignoredEntitiesBuffer)
{
if (OrbitCameraUtilities.TryGetCameraTargetInterpolatedWorldTransform(
cameraControl.FollowedCharacterEntity,
ref LocalToWorldLookup,
ref CameraTargetLookup,
out LocalToWorld targetWorldTransform))
{
quaternion cameraRotation = OrbitCameraUtilities.CalculateCameraRotation(targetWorldTransform.Up, orbitCamera.PlanarForward, orbitCamera.PitchAngle);
float3 cameraForward = math.mul(cameraRotation, math.forward());
float3 targetPosition = targetWorldTransform.Position;
// Distance smoothing
orbitCamera.SmoothedTargetDistance = math.lerp(orbitCamera.SmoothedTargetDistance, orbitCamera.TargetDistance, MathUtilities.GetSharpnessInterpolant(orbitCamera.DistanceMovementSharpness, DeltaTime));
// Obstruction handling
// Obstruction detection is handled here, because we have to adjust the obstruction distance
// to match the interpolated physics body transform (as opposed to the "simulation" transform). Otherwise, a
// camera getting obstructed by a moving physics body would have visible jitter.
if (orbitCamera.ObstructionRadius > 0f)
{
float obstructionCheckDistance = orbitCamera.SmoothedTargetDistance;
CameraObstructionHitsCollector collector = new CameraObstructionHitsCollector(cameraControl.FollowedCharacterEntity, ignoredEntitiesBuffer, cameraForward);
PhysicsWorld.SphereCastCustom(
targetPosition,
orbitCamera.ObstructionRadius,
-cameraForward,
obstructionCheckDistance,
ref collector,
CollisionFilter.Default,
QueryInteraction.IgnoreTriggers);
float newObstructedDistance = obstructionCheckDistance;
if (collector.NumHits > 0)
{
newObstructedDistance = obstructionCheckDistance * collector.ClosestHit.Fraction;
// Redo cast with the interpolated body transform to prevent FixedUpdate jitter in obstruction detection
if (orbitCamera.PreventFixedUpdateJitter)
{
RigidBody hitBody = PhysicsWorld.Bodies[collector.ClosestHit.RigidBodyIndex];
if (LocalToWorldLookup.TryGetComponent(hitBody.Entity, out LocalToWorld hitBodyLocalToWorld))
{
// Adjust the rigidbody transform for interpolation, so we can raycast it in that state
hitBody.WorldFromBody = new RigidTransform(quaternion.LookRotationSafe(hitBodyLocalToWorld.Forward, hitBodyLocalToWorld.Up), hitBodyLocalToWorld.Position);
collector = new CameraObstructionHitsCollector(cameraControl.FollowedCharacterEntity, ignoredEntitiesBuffer, cameraForward);
hitBody.SphereCastCustom(
targetPosition,
orbitCamera.ObstructionRadius,
-cameraForward,
obstructionCheckDistance,
ref collector,
CollisionFilter.Default,
QueryInteraction.IgnoreTriggers);
if (collector.NumHits > 0)
{
newObstructedDistance = obstructionCheckDistance * collector.ClosestHit.Fraction;
}
}
}
}
// Update current distance based on obstructed distance
if (orbitCamera.ObstructedDistance < newObstructedDistance)
{
// Move outer
orbitCamera.ObstructedDistance = math.lerp(orbitCamera.ObstructedDistance, newObstructedDistance, MathUtilities.GetSharpnessInterpolant(orbitCamera.ObstructionOuterSmoothingSharpness, DeltaTime));
}
else if (orbitCamera.ObstructedDistance > newObstructedDistance)
{
// Move inner
orbitCamera.ObstructedDistance = math.lerp(orbitCamera.ObstructedDistance, newObstructedDistance, MathUtilities.GetSharpnessInterpolant(orbitCamera.ObstructionInnerSmoothingSharpness, DeltaTime));
}
}
else
{
orbitCamera.ObstructedDistance = orbitCamera.SmoothedTargetDistance;
}
// Place camera at the final distance (includes smoothing and obstructions)
float3 cameraPosition = OrbitCameraUtilities.CalculateCameraPosition(targetPosition, cameraRotation, orbitCamera.ObstructedDistance);
// Write to LtW
LocalToWorldLookup[entity] = new LocalToWorld { Value = new float4x4(cameraRotation, cameraPosition) };
}
}
}
}
public static class OrbitCameraUtilities
{
public static bool TryGetCameraTargetSimulationWorldTransform(
Entity targetCharacterEntity,
ref ComponentLookup<LocalTransform> localTransformLookup,
ref ComponentLookup<Parent> parentLookup,
ref ComponentLookup<PostTransformMatrix> postTransformMatrixLookup,
ref ComponentLookup<CameraTarget> cameraTargetLookup,
out float4x4 worldTransform)
{
bool foundValidCameraTarget = false;
worldTransform = float4x4.identity;
// Camera target is either defined by the CameraTarget component, or if not, the transform of the followed character
if (cameraTargetLookup.TryGetComponent(targetCharacterEntity, out CameraTarget cameraTarget) &&
localTransformLookup.HasComponent(cameraTarget.TargetEntity))
{
TransformHelpers.ComputeWorldTransformMatrix(
cameraTarget.TargetEntity,
out worldTransform,
ref localTransformLookup,
ref parentLookup,
ref postTransformMatrixLookup);
foundValidCameraTarget = true;
}
else if (localTransformLookup.TryGetComponent(targetCharacterEntity, out LocalTransform characterLocalTransform))
{
worldTransform = float4x4.TRS(characterLocalTransform.Position, characterLocalTransform.Rotation, 1f);
foundValidCameraTarget = true;
}
return foundValidCameraTarget;
}
public static bool TryGetCameraTargetInterpolatedWorldTransform(
Entity targetCharacterEntity,
ref ComponentLookup<LocalToWorld> localToWorldLookup,
ref ComponentLookup<CameraTarget> cameraTargetLookup,
out LocalToWorld worldTransform)
{
bool foundValidCameraTarget = false;
worldTransform = default;
// Get the interpolated transform of the target
if (cameraTargetLookup.TryGetComponent(targetCharacterEntity, out CameraTarget cameraTarget) &&
localToWorldLookup.TryGetComponent(cameraTarget.TargetEntity, out worldTransform))
{
foundValidCameraTarget = true;
}
else if (localToWorldLookup.TryGetComponent(targetCharacterEntity, out worldTransform))
{
foundValidCameraTarget = true;
}
return foundValidCameraTarget;
}
public static quaternion CalculateCameraRotation(float3 targetUp, float3 planarForward, float pitchAngle)
{
quaternion pitchRotation = quaternion.Euler(math.right() * math.radians(pitchAngle));
quaternion cameraRotation = MathUtilities.CreateRotationWithUpPriority(targetUp, planarForward);
cameraRotation = math.mul(cameraRotation, pitchRotation);
return cameraRotation;
}
public static float3 CalculateCameraPosition(float3 targetPosition, quaternion cameraRotation, float distance)
{
return targetPosition + (-MathUtilities.GetForwardFromRotation(cameraRotation) * distance);
}
}
public struct CameraObstructionHitsCollector : ICollector<ColliderCastHit>
{
public bool EarlyOutOnFirstHit => false;
public float MaxFraction => 1f;
public int NumHits { get; private set; }
public ColliderCastHit ClosestHit;
private float _closestHitFraction;
private float3 _cameraDirection;
private Entity _followedCharacter;
private DynamicBuffer<OrbitCameraIgnoredEntityBufferElement> _ignoredEntitiesBuffer;
public CameraObstructionHitsCollector(Entity followedCharacter, DynamicBuffer<OrbitCameraIgnoredEntityBufferElement> ignoredEntitiesBuffer, float3 cameraDirection)
{
NumHits = 0;
ClosestHit = default;
_closestHitFraction = float.MaxValue;
_cameraDirection = cameraDirection;
_followedCharacter = followedCharacter;
_ignoredEntitiesBuffer = ignoredEntitiesBuffer;
}
public bool AddHit(ColliderCastHit hit)
{
if (_followedCharacter == hit.Entity)
{
return false;
}
if (math.dot(hit.SurfaceNormal, _cameraDirection) < 0f || !PhysicsUtilities.IsCollidable(hit.Material))
{
return false;
}
for (int i = 0; i < _ignoredEntitiesBuffer.Length; i++)
{
if (_ignoredEntitiesBuffer[i].Entity == hit.Entity)
{
return false;
}
}
// Process valid hit
if (hit.Fraction < _closestHitFraction)
{
_closestHitFraction = hit.Fraction;
ClosestHit = hit;
}
NumHits++;
return true;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6d6d36bc694f390408f5683be8de8c7d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,224 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.CharacterController;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Physics.Authoring;
using Unity.Physics.Extensions;
using Unity.Physics.Systems;
using Unity.Transforms;
using UnityEngine;
public struct ThirdPersonCharacterUpdateContext
{
// Here, you may add additional global data for your character updates, such as ComponentLookups, Singletons, NativeCollections, etc...
// The data you add here will be accessible in your character updates and all of your character "callbacks".
public void OnSystemCreate(ref SystemState state)
{
// Get lookups
}
public void OnSystemUpdate(ref SystemState state)
{
// Update lookups
}
}
public readonly partial struct ThirdPersonCharacterAspect : IAspect, IKinematicCharacterProcessor<ThirdPersonCharacterUpdateContext>
{
public readonly KinematicCharacterAspect CharacterAspect;
public readonly RefRW<ThirdPersonCharacterComponent> CharacterComponent;
public readonly RefRW<ThirdPersonCharacterControl> CharacterControl;
public void PhysicsUpdate(ref ThirdPersonCharacterUpdateContext context, ref KinematicCharacterUpdateContext baseContext)
{
ref ThirdPersonCharacterComponent characterComponent = ref CharacterComponent.ValueRW;
ref KinematicCharacterBody characterBody = ref CharacterAspect.CharacterBody.ValueRW;
ref float3 characterPosition = ref CharacterAspect.LocalTransform.ValueRW.Position;
// First phase of default character update
CharacterAspect.Update_Initialize(in this, ref context, ref baseContext, ref characterBody, baseContext.Time.DeltaTime);
CharacterAspect.Update_ParentMovement(in this, ref context, ref baseContext, ref characterBody, ref characterPosition, characterBody.WasGroundedBeforeCharacterUpdate);
CharacterAspect.Update_Grounding(in this, ref context, ref baseContext, ref characterBody, ref characterPosition);
// Update desired character velocity after grounding was detected, but before doing additional processing that depends on velocity
HandleVelocityControl(ref context, ref baseContext);
// Second phase of default character update
CharacterAspect.Update_PreventGroundingFromFutureSlopeChange(in this, ref context, ref baseContext, ref characterBody, in characterComponent.StepAndSlopeHandling);
CharacterAspect.Update_GroundPushing(in this, ref context, ref baseContext, characterComponent.Gravity);
CharacterAspect.Update_MovementAndDecollisions(in this, ref context, ref baseContext, ref characterBody, ref characterPosition);
CharacterAspect.Update_MovingPlatformDetection(ref baseContext, ref characterBody);
CharacterAspect.Update_ParentMomentum(ref baseContext, ref characterBody);
CharacterAspect.Update_ProcessStatefulCharacterHits();
}
private void HandleVelocityControl(ref ThirdPersonCharacterUpdateContext context, ref KinematicCharacterUpdateContext baseContext)
{
float deltaTime = baseContext.Time.DeltaTime;
ref KinematicCharacterBody characterBody = ref CharacterAspect.CharacterBody.ValueRW;
ref ThirdPersonCharacterComponent characterComponent = ref CharacterComponent.ValueRW;
ref ThirdPersonCharacterControl characterControl = ref CharacterControl.ValueRW;
// Rotate move input and velocity to take into account parent rotation
if(characterBody.ParentEntity != Entity.Null)
{
characterControl.MoveVector = math.rotate(characterBody.RotationFromParent, characterControl.MoveVector);
characterBody.RelativeVelocity = math.rotate(characterBody.RotationFromParent, characterBody.RelativeVelocity);
}
if (characterBody.IsGrounded)
{
// Move on ground
float3 targetVelocity = characterControl.MoveVector * characterComponent.GroundMaxSpeed;
CharacterControlUtilities.StandardGroundMove_Interpolated(ref characterBody.RelativeVelocity, targetVelocity, characterComponent.GroundedMovementSharpness, deltaTime, characterBody.GroundingUp, characterBody.GroundHit.Normal);
// Jump
if (characterControl.Jump)
{
CharacterControlUtilities.StandardJump(ref characterBody, characterBody.GroundingUp * characterComponent.JumpSpeed, true, characterBody.GroundingUp);
}
}
else
{
// Move in air
float3 airAcceleration = characterControl.MoveVector * characterComponent.AirAcceleration;
if (math.lengthsq(airAcceleration) > 0f)
{
float3 tmpVelocity = characterBody.RelativeVelocity;
CharacterControlUtilities.StandardAirMove(ref characterBody.RelativeVelocity, airAcceleration, characterComponent.AirMaxSpeed, characterBody.GroundingUp, deltaTime, false);
// Cancel air acceleration from input if we would hit a non-grounded surface (prevents air-climbing slopes at high air accelerations)
if (characterComponent.PreventAirAccelerationAgainstUngroundedHits && CharacterAspect.MovementWouldHitNonGroundedObstruction(in this, ref context, ref baseContext, characterBody.RelativeVelocity * deltaTime, out ColliderCastHit hit))
{
characterBody.RelativeVelocity = tmpVelocity;
}
}
// Gravity
CharacterControlUtilities.AccelerateVelocity(ref characterBody.RelativeVelocity, characterComponent.Gravity, deltaTime);
// Drag
CharacterControlUtilities.ApplyDragToVelocity(ref characterBody.RelativeVelocity, deltaTime, characterComponent.AirDrag);
}
}
public void VariableUpdate(ref ThirdPersonCharacterUpdateContext context, ref KinematicCharacterUpdateContext baseContext)
{
ref KinematicCharacterBody characterBody = ref CharacterAspect.CharacterBody.ValueRW;
ref ThirdPersonCharacterComponent characterComponent = ref CharacterComponent.ValueRW;
ref ThirdPersonCharacterControl characterControl = ref CharacterControl.ValueRW;
ref quaternion characterRotation = ref CharacterAspect.LocalTransform.ValueRW.Rotation;
// Add rotation from parent body to the character rotation
// (this is for allowing a rotating moving platform to rotate your character as well, and handle interpolation properly)
KinematicCharacterUtilities.AddVariableRateRotationFromFixedRateRotation(ref characterRotation, characterBody.RotationFromParent, baseContext.Time.DeltaTime, characterBody.LastPhysicsUpdateDeltaTime);
// Rotate towards move direction
if (math.lengthsq(characterControl.MoveVector) > 0f)
{
CharacterControlUtilities.SlerpRotationTowardsDirectionAroundUp(ref characterRotation, baseContext.Time.DeltaTime, math.normalizesafe(characterControl.MoveVector), MathUtilities.GetUpFromRotation(characterRotation), characterComponent.RotationSharpness);
}
}
#region Character Processor Callbacks
public void UpdateGroundingUp(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext)
{
ref KinematicCharacterBody characterBody = ref CharacterAspect.CharacterBody.ValueRW;
CharacterAspect.Default_UpdateGroundingUp(ref characterBody);
}
public bool CanCollideWithHit(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext,
in BasicHit hit)
{
return PhysicsUtilities.IsCollidable(hit.Material);
}
public bool IsGroundedOnHit(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext,
in BasicHit hit,
int groundingEvaluationType)
{
ThirdPersonCharacterComponent characterComponent = CharacterComponent.ValueRO;
return CharacterAspect.Default_IsGroundedOnHit(
in this,
ref context,
ref baseContext,
in hit,
in characterComponent.StepAndSlopeHandling,
groundingEvaluationType);
}
public void OnMovementHit(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext,
ref KinematicCharacterHit hit,
ref float3 remainingMovementDirection,
ref float remainingMovementLength,
float3 originalVelocityDirection,
float hitDistance)
{
ref KinematicCharacterBody characterBody = ref CharacterAspect.CharacterBody.ValueRW;
ref float3 characterPosition = ref CharacterAspect.LocalTransform.ValueRW.Position;
ThirdPersonCharacterComponent characterComponent = CharacterComponent.ValueRO;
CharacterAspect.Default_OnMovementHit(
in this,
ref context,
ref baseContext,
ref characterBody,
ref characterPosition,
ref hit,
ref remainingMovementDirection,
ref remainingMovementLength,
originalVelocityDirection,
hitDistance,
characterComponent.StepAndSlopeHandling.StepHandling,
characterComponent.StepAndSlopeHandling.MaxStepHeight,
characterComponent.StepAndSlopeHandling.CharacterWidthForStepGroundingCheck);
}
public void OverrideDynamicHitMasses(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext,
ref PhysicsMass characterMass,
ref PhysicsMass otherMass,
BasicHit hit)
{
// Custom mass overrides
}
public void ProjectVelocityOnHits(
ref ThirdPersonCharacterUpdateContext context,
ref KinematicCharacterUpdateContext baseContext,
ref float3 velocity,
ref bool characterIsGrounded,
ref BasicHit characterGroundHit,
in DynamicBuffer<KinematicVelocityProjectionHit> velocityProjectionHits,
float3 originalVelocityDirection)
{
ThirdPersonCharacterComponent characterComponent = CharacterComponent.ValueRO;
CharacterAspect.Default_ProjectVelocityOnHits(
ref velocity,
ref characterIsGrounded,
ref characterGroundHit,
in velocityProjectionHits,
originalVelocityDirection,
characterComponent.StepAndSlopeHandling.ConstrainVelocityToGroundPlane);
}
#endregion
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2e1982b631c39194b8eaa4838ec11284
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,50 @@
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics.Authoring;
using UnityEngine;
using Unity.CharacterController;
using Unity.Physics;
using UnityEngine.Serialization;
[DisallowMultipleComponent]
public class ThirdPersonCharacterAuthoring : MonoBehaviour
{
public AuthoringKinematicCharacterProperties CharacterProperties = AuthoringKinematicCharacterProperties.GetDefault();
public float RotationSharpness = 25f;
public float GroundMaxSpeed = 10f;
public float GroundedMovementSharpness = 15f;
public float AirAcceleration = 50f;
public float AirMaxSpeed = 10f;
public float AirDrag = 0f;
public float JumpSpeed = 10f;
public float3 Gravity = math.up() * -30f;
public bool PreventAirAccelerationAgainstUngroundedHits = true;
public BasicStepAndSlopeHandlingParameters StepAndSlopeHandling = BasicStepAndSlopeHandlingParameters.GetDefault();
public class Baker : Baker<ThirdPersonCharacterAuthoring>
{
public override void Bake(ThirdPersonCharacterAuthoring authoring)
{
KinematicCharacterUtilities.BakeCharacter(this, authoring.gameObject, authoring.CharacterProperties);
Entity entity = GetEntity(TransformUsageFlags.Dynamic | TransformUsageFlags.WorldSpace);
AddComponent(entity, new ThirdPersonCharacterComponent
{
RotationSharpness = authoring.RotationSharpness,
GroundMaxSpeed = authoring.GroundMaxSpeed,
GroundedMovementSharpness = authoring.GroundedMovementSharpness,
AirAcceleration = authoring.AirAcceleration,
AirMaxSpeed = authoring.AirMaxSpeed,
AirDrag = authoring.AirDrag,
JumpSpeed = authoring.JumpSpeed,
Gravity = authoring.Gravity,
PreventAirAccelerationAgainstUngroundedHits = authoring.PreventAirAccelerationAgainstUngroundedHits,
StepAndSlopeHandling = authoring.StepAndSlopeHandling,
});
AddComponent(entity, new ThirdPersonCharacterControl());
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c854a728d43c7cf47bec103607a449f9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,28 @@
using System;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
using Unity.CharacterController;
[Serializable]
public struct ThirdPersonCharacterComponent : IComponentData
{
public float RotationSharpness;
public float GroundMaxSpeed;
public float GroundedMovementSharpness;
public float AirAcceleration;
public float AirMaxSpeed;
public float AirDrag;
public float JumpSpeed;
public float3 Gravity;
public bool PreventAirAccelerationAgainstUngroundedHits;
public BasicStepAndSlopeHandlingParameters StepAndSlopeHandling;
}
[Serializable]
public struct ThirdPersonCharacterControl : IComponentData
{
public float3 MoveVector;
public bool Jump;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d8471dfde63584745b2234708055b211
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,137 @@
using Unity.Burst;
using Unity.Entities;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Transforms;
using Unity.CharacterController;
using Unity.Burst.Intrinsics;
[UpdateInGroup(typeof(KinematicCharacterPhysicsUpdateGroup))]
[BurstCompile]
public partial struct ThirdPersonCharacterPhysicsUpdateSystem : ISystem
{
private EntityQuery _characterQuery;
private ThirdPersonCharacterUpdateContext _context;
private KinematicCharacterUpdateContext _baseContext;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
_characterQuery = KinematicCharacterUtilities.GetBaseCharacterQueryBuilder()
.WithAll<
ThirdPersonCharacterComponent,
ThirdPersonCharacterControl>()
.Build(ref state);
_context = new ThirdPersonCharacterUpdateContext();
_context.OnSystemCreate(ref state);
_baseContext = new KinematicCharacterUpdateContext();
_baseContext.OnSystemCreate(ref state);
state.RequireForUpdate(_characterQuery);
state.RequireForUpdate<PhysicsWorldSingleton>();
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
_context.OnSystemUpdate(ref state);
_baseContext.OnSystemUpdate(ref state, SystemAPI.Time, SystemAPI.GetSingleton<PhysicsWorldSingleton>());
ThirdPersonCharacterPhysicsUpdateJob job = new ThirdPersonCharacterPhysicsUpdateJob
{
Context = _context,
BaseContext = _baseContext,
};
job.ScheduleParallel();
}
[BurstCompile]
[WithAll(typeof(Simulate))]
public partial struct ThirdPersonCharacterPhysicsUpdateJob : IJobEntity, IJobEntityChunkBeginEnd
{
public ThirdPersonCharacterUpdateContext Context;
public KinematicCharacterUpdateContext BaseContext;
void Execute(ThirdPersonCharacterAspect characterAspect)
{
characterAspect.PhysicsUpdate(ref Context, ref BaseContext);
}
public bool OnChunkBegin(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
BaseContext.EnsureCreationOfTmpCollections();
return true;
}
public void OnChunkEnd(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask, bool chunkWasExecuted)
{ }
}
}
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(ThirdPersonPlayerVariableStepControlSystem))]
[UpdateBefore(typeof(TransformSystemGroup))]
[BurstCompile]
public partial struct ThirdPersonCharacterVariableUpdateSystem : ISystem
{
private EntityQuery _characterQuery;
private ThirdPersonCharacterUpdateContext _context;
private KinematicCharacterUpdateContext _baseContext;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
_characterQuery = KinematicCharacterUtilities.GetBaseCharacterQueryBuilder()
.WithAll<
ThirdPersonCharacterComponent,
ThirdPersonCharacterControl>()
.Build(ref state);
_context = new ThirdPersonCharacterUpdateContext();
_context.OnSystemCreate(ref state);
_baseContext = new KinematicCharacterUpdateContext();
_baseContext.OnSystemCreate(ref state);
state.RequireForUpdate(_characterQuery);
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
_context.OnSystemUpdate(ref state);
_baseContext.OnSystemUpdate(ref state, SystemAPI.Time, SystemAPI.GetSingleton<PhysicsWorldSingleton>());
ThirdPersonCharacterVariableUpdateJob job = new ThirdPersonCharacterVariableUpdateJob
{
Context = _context,
BaseContext = _baseContext,
};
job.ScheduleParallel();
}
[BurstCompile]
[WithAll(typeof(Simulate))]
public partial struct ThirdPersonCharacterVariableUpdateJob : IJobEntity, IJobEntityChunkBeginEnd
{
public ThirdPersonCharacterUpdateContext Context;
public KinematicCharacterUpdateContext BaseContext;
void Execute(ThirdPersonCharacterAspect characterAspect)
{
characterAspect.VariableUpdate(ref Context, ref BaseContext);
}
public bool OnChunkBegin(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
BaseContext.EnsureCreationOfTmpCollections();
return true;
}
public void OnChunkEnd(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask, bool chunkWasExecuted)
{ }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b37392a281d8a5f45a770ad4cfd747a6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using System;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
[Serializable]
public struct ThirdPersonPlayer : IComponentData
{
public Entity ControlledCharacter;
public Entity ControlledCamera;
}
[Serializable]
public struct ThirdPersonPlayerInputs : IComponentData
{
public float2 MoveInput;
public float2 CameraLookInput;
public float CameraZoomInput;
public FixedInputEvent JumpPressed;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8586d18bf7667c040949956b7ff40b6d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
using UnityEngine;
using Unity.Entities;
[DisallowMultipleComponent]
public class ThirdPersonPlayerAuthoring : MonoBehaviour
{
public GameObject ControlledCharacter;
public GameObject ControlledCamera;
public class Baker : Baker<ThirdPersonPlayerAuthoring>
{
public override void Bake(ThirdPersonPlayerAuthoring authoring)
{
Entity entity = GetEntity(TransformUsageFlags.None);
AddComponent(entity, new ThirdPersonPlayer
{
ControlledCharacter = GetEntity(authoring.ControlledCharacter, TransformUsageFlags.Dynamic),
ControlledCamera = GetEntity(authoring.ControlledCamera, TransformUsageFlags.Dynamic),
});
AddComponent<ThirdPersonPlayerInputs>(entity);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3fbdb3174a73a07408595a85d3e7fb6a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,127 @@
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Unity.CharacterController;
[UpdateInGroup(typeof(InitializationSystemGroup))]
public partial class ThirdPersonPlayerInputsSystem : SystemBase
{
protected override void OnCreate()
{
RequireForUpdate<FixedTickSystem.Singleton>();
RequireForUpdate(SystemAPI.QueryBuilder().WithAll<ThirdPersonPlayer, ThirdPersonPlayerInputs>().Build());
}
protected override void OnUpdate()
{
uint tick = SystemAPI.GetSingleton<FixedTickSystem.Singleton>().Tick;
foreach (var (playerInputs, player) in SystemAPI.Query<RefRW<ThirdPersonPlayerInputs>, ThirdPersonPlayer>())
{
playerInputs.ValueRW.MoveInput = new float2
{
x = (Input.GetKey(KeyCode.D) ? 1f : 0f) + (Input.GetKey(KeyCode.A) ? -1f : 0f),
y = (Input.GetKey(KeyCode.W) ? 1f : 0f) + (Input.GetKey(KeyCode.S) ? -1f : 0f),
};
playerInputs.ValueRW.CameraLookInput = new float2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
playerInputs.ValueRW.CameraZoomInput = -Input.mouseScrollDelta.y;
if (Input.GetKeyDown(KeyCode.Space))
{
playerInputs.ValueRW.JumpPressed.Set(tick);
}
}
}
}
/// <summary>
/// Apply inputs that need to be read at a variable rate
/// </summary>
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(FixedStepSimulationSystemGroup))]
[BurstCompile]
public partial struct ThirdPersonPlayerVariableStepControlSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<ThirdPersonPlayer, ThirdPersonPlayerInputs>().Build());
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
foreach (var (playerInputs, player) in SystemAPI.Query<ThirdPersonPlayerInputs, ThirdPersonPlayer>().WithAll<Simulate>())
{
if (SystemAPI.HasComponent<OrbitCameraControl>(player.ControlledCamera))
{
OrbitCameraControl cameraControl = SystemAPI.GetComponent<OrbitCameraControl>(player.ControlledCamera);
cameraControl.FollowedCharacterEntity = player.ControlledCharacter;
cameraControl.LookDegreesDelta = playerInputs.CameraLookInput;
cameraControl.ZoomDelta = playerInputs.CameraZoomInput;
SystemAPI.SetComponent(player.ControlledCamera, cameraControl);
}
}
}
}
/// <summary>
/// Apply inputs that need to be read at a fixed rate.
/// It is necessary to handle this as part of the fixed step group, in case your framerate is lower than the fixed step rate.
/// </summary>
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup), OrderFirst = true)]
[BurstCompile]
public partial struct ThirdPersonPlayerFixedStepControlSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<FixedTickSystem.Singleton>();
state.RequireForUpdate(SystemAPI.QueryBuilder().WithAll<ThirdPersonPlayer, ThirdPersonPlayerInputs>().Build());
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
uint tick = SystemAPI.GetSingleton<FixedTickSystem.Singleton>().Tick;
foreach (var (playerInputs, player) in SystemAPI.Query<ThirdPersonPlayerInputs, ThirdPersonPlayer>().WithAll<Simulate>())
{
if (SystemAPI.HasComponent<ThirdPersonCharacterControl>(player.ControlledCharacter))
{
ThirdPersonCharacterControl characterControl = SystemAPI.GetComponent<ThirdPersonCharacterControl>(player.ControlledCharacter);
float3 characterUp = MathUtilities.GetUpFromRotation(SystemAPI.GetComponent<LocalTransform>(player.ControlledCharacter).Rotation);
// Get camera rotation, since our movement is relative to it.
quaternion cameraRotation = quaternion.identity;
if (SystemAPI.HasComponent<OrbitCamera>(player.ControlledCamera))
{
// Camera rotation is calculated rather than gotten from transform, because this allows us to
// reduce the size of the camera ghost state in a netcode prediction context.
// If not using netcode prediction, we could simply get rotation from transform here instead.
OrbitCamera orbitCamera = SystemAPI.GetComponent<OrbitCamera>(player.ControlledCamera);
cameraRotation = OrbitCameraUtilities.CalculateCameraRotation(characterUp, orbitCamera.PlanarForward, orbitCamera.PitchAngle);
}
float3 cameraForwardOnUpPlane = math.normalizesafe(MathUtilities.ProjectOnPlane(MathUtilities.GetForwardFromRotation(cameraRotation), characterUp));
float3 cameraRight = MathUtilities.GetRightFromRotation(cameraRotation);
// Move
characterControl.MoveVector = (playerInputs.MoveInput.y * cameraForwardOnUpPlane) + (playerInputs.MoveInput.x * cameraRight);
characterControl.MoveVector = MathUtilities.ClampToMaxLength(characterControl.MoveVector, 1f);
// Jump
characterControl.Jump = playerInputs.JumpPressed.IsSet(tick);
SystemAPI.SetComponent(player.ControlledCharacter, characterControl);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 427fac77ddc96db4a87e6d5b4a31555f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: