1
NGUI 3 Support / SpringDampen Performance optimization
« on: July 05, 2013, 11:15:25 PM »
Noticed this was starting to eat up some CPU cycles and the current implementation seemed odd. This is roughly 4x faster than the current method (rough benchmark).
Original Way:
Faster Way (Use raw math instead of a loop)
Original Way:
- static public Vector3 SpringDampen (ref Vector3 velocity, float strength, float deltaTime)
- {
- // Dampening factor applied each millisecond
- if (deltaTime > 1f) deltaTime = 1f;
- float dampeningFactor = 1f - strength * 0.001f;
- int ms = Mathf.RoundToInt(deltaTime * 1000f);
- Vector3 offset = Vector3.zero;
- // Apply the offset for each millisecond
- for (int i = 0; i < ms; ++i)
- {
- // Mimic 60 FPS the editor runs at
- offset += velocity * 0.06f;
- velocity *= dampeningFactor;
- }
- return offset;
- }
Faster Way (Use raw math instead of a loop)
- static public Vector3 SpringDampen (ref Vector3 velocity, float strength, float deltaTime)
- {
- // Dampening factor applied each millisecond
- if (deltaTime > 1f) deltaTime = 1f;
- float dampeningFactor = 1f - strength * 0.001f;
- int ms = Mathf.RoundToInt(deltaTime * 1000f);
- float totalDampening = Mathf.Pow(dampeningFactor, ms);
- Vector3 vTotal = velocity * ((totalDampening - 1f) / Mathf.Log(dampeningFactor));
- velocity = velocity * totalDampening;
- return vTotal * .06f;
- }
