This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public struct ProjectedBody | |
{ | |
public const float DampingDefault = 0.01f; | |
public const float TimeStep = 1f / 60f; | |
public static readonly float3 Gravity = new float3(0f, -9.81f, 0f); | |
public float3 StartPosition; | |
public float Damping; | |
public float3 Velocity; | |
public float3 Position; | |
public quaternion Rotation; | |
public static ProjectedBody Create(float3 position, Quaternion rotation, float force, float angle, float damping, PhysicsMass mass) | |
{ | |
ProjectedBody body = new ProjectedBody(); | |
body.Damping = damping; | |
body.Position = position; | |
body.StartPosition = position; | |
rotation = rotation * Quaternion.Euler(angle, 0f, 0f); | |
LocalToWorld transform = new LocalToWorld { Value = float4x4.TRS(body.Position, rotation, new float3(1f, 1f, 1f)) }; | |
PhysicsVelocity velocity = default; | |
velocity.ApplyLinearImpulse(mass, transform.Forward * force); | |
body.Velocity = velocity.Linear; | |
return body; | |
} | |
public static void ApplyGravityToVelocity(ref float3 velocity, float timeStep, float3 gravity, float gravityFactor = 1f) | |
{ | |
float3 gravityAcceleration = timeStep * gravity; | |
velocity += gravityAcceleration * gravityFactor; | |
} | |
public static void UpdatePositionWithVelocity(ref float3 position, float3 velocity, float timeStep) | |
{ | |
position += velocity * timeStep; | |
} | |
public void Step(float timeStep = TimeStep) | |
{ | |
ApplyGravityToVelocity(ref Velocity, timeStep, Gravity, 1f); | |
Velocity *= math.clamp(1.0f - Damping * timeStep, 0.0f, 1.0f); | |
UpdatePositionWithVelocity(ref Position, Velocity, timeStep); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment