Skip to content

Instantly share code, notes, and snippets.

@gamemachine
Last active June 27, 2021 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamemachine/9b4ce6eef9c1060409de47493b84000a to your computer and use it in GitHub Desktop.
Save gamemachine/9b4ce6eef9c1060409de47493b84000a to your computer and use it in GitHub Desktop.
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