Last active
April 3, 2017 19:53
-
-
Save OhiraKyou/c98ec855fa97c8fce88955174c8d2894 to your computer and use it in GitHub Desktop.
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
using System.Collections.Generic; | |
using UnityEngine; | |
namespace OhiraKyou.Extensions { | |
public static class RigidbodyExtensions { | |
private static Dictionary<Rigidbody, Vector3[]> velocities = new Dictionary<Rigidbody, Vector3[]>(); | |
private const int VELOCITY_INDEX = 0; | |
private const int ANGULAR_VELOCITY_INDEX = 1; | |
public static void Pause (this Rigidbody rb) { | |
RemoveNullVelocities(); | |
// Assign velocities to rigidbody's current velocities | |
Vector3[] newVelocities = new Vector3[2]; | |
newVelocities[VELOCITY_INDEX] = rb.velocity; | |
newVelocities[ANGULAR_VELOCITY_INDEX] = rb.angularVelocity; | |
if (velocities.ContainsKey(rb)) { | |
velocities[rb] = newVelocities; | |
} else { | |
velocities.Add(rb, newVelocities); | |
} | |
// Freeze rigidbody last to ensure velocities get saved properly | |
rb.isKinematic = true; | |
} | |
public static void UnPause (this Rigidbody rb) { | |
RemoveNullVelocities(); | |
// Unfreeze rigidbody first to ensure the velocity application works | |
rb.isKinematic = false; | |
// Return velocities to their pre-frozen values) | |
Vector3[] associatedVelocities; | |
if (velocities.TryGetValue(rb, out associatedVelocities)) { | |
rb.velocity = associatedVelocities[VELOCITY_INDEX]; | |
rb.angularVelocity = associatedVelocities[ANGULAR_VELOCITY_INDEX]; | |
// Definition has served its temporary purpose; remove it | |
velocities.Remove(rb); | |
} | |
} | |
public static void ClearVelocity (this Rigidbody rb) { | |
rb.velocity = Vector3.zero; | |
rb.angularVelocity = Vector3.zero; | |
} | |
private static void RemoveNullVelocities () { | |
velocities = velocities.WithoutNullKeys<Rigidbody, Vector3[]>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment