GibTreaty

Physics Simulator

Jun 12th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. public static class PhysicsSimulator {
  2.         /// <summary>
  3.         /// Add force to velocity
  4.         /// </summary>
  5.         public static Vector3 AddForce(this Vector3 velocity, Vector3 force, float mass, ForceMode forceMode = ForceMode.Force) {
  6.             switch(forceMode) {
  7.                 case ForceMode.Force:
  8.                     velocity += (force / mass) * Time.fixedDeltaTime; break;
  9.                 case ForceMode.Acceleration:
  10.                     velocity += force * Time.fixedDeltaTime; break;
  11.                 case ForceMode.Impulse:
  12.                     velocity += force / mass; break;
  13.                 case ForceMode.VelocityChange:
  14.                     velocity += force; break;
  15.             }
  16.  
  17.             return velocity;
  18.         }
  19.  
  20.         /// <summary>
  21.         /// Get just the force without adding it to velocity
  22.         /// </summary>
  23.         public static Vector3 GetForce(this Vector3 force, float mass, ForceMode forceMode = ForceMode.Force) {
  24.             switch(forceMode) {
  25.                 case ForceMode.Force:
  26.                     return (force / mass) * Time.fixedDeltaTime;
  27.                 case ForceMode.Acceleration:
  28.                     return force * Time.fixedDeltaTime;
  29.                 case ForceMode.Impulse:
  30.                     return force / mass;
  31.                 case ForceMode.VelocityChange:
  32.                     return force;
  33.             }
  34.  
  35.             return Vector3.zero;
  36.         }
  37.  
  38.         /// <summary>
  39.         /// Moves a position based on acceleration and drag
  40.         /// </summary>
  41.         public static Vector3 SimulatePosition(this Vector3 position, Vector3 velocity, Vector3 acceleration, float drag = 0) {
  42.             velocity += acceleration * Time.deltaTime;
  43.             velocity -= velocity * drag * Time.deltaTime;
  44.  
  45.             return position + velocity * Time.deltaTime;
  46.         }
  47.  
  48.         /// <summary>
  49.         /// Applies acceleration and drag to the velocity
  50.         /// </summary>
  51.         public static Vector3 SimulateVelocity(this Vector3 velocity, Vector3 acceleration, float drag = 0) {
  52.             velocity += acceleration * Time.deltaTime;
  53.             velocity -= velocity * drag * Time.deltaTime;
  54.  
  55.             return velocity;
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment