| [3] | 1 | // Fidget spinner logic. |
|---|
| 2 | // This class represents a fidget spinner that can be spun to a specified |
|---|
| 3 | // velocity and then over time will slow down and stop. The spinner keeps track |
|---|
| 4 | // of its continuous (floating point) position value within the range 0...<10 |
|---|
| 5 | // so it can map to CircuitPlayground pixel positions easily.// Author: Tony DiCola |
|---|
| 6 | // License: MIT License (https://opensource.org/licenses/MIT) |
|---|
| 7 | // Usage: |
|---|
| 8 | // - Create an instance of the class (specifying a custom decay value between 0 and 1, |
|---|
| 9 | // the lower the decay the faster the spinner slows down). |
|---|
| 10 | // - Call spin to start the spinner moving at the specified velocity (in pixels/second). |
|---|
| 11 | // - Call getPosition periodically to get the current spinner position given an elapsed |
|---|
| 12 | // amount of seconds since the last getPosition call. |
|---|
| 13 | #ifndef FIDGETANIMATION_H |
|---|
| 14 | #define FIDGETANIMATION_H |
|---|
| 15 | |
|---|
| 16 | class FidgetSpinner { |
|---|
| 17 | public: |
|---|
| 18 | FidgetSpinner(float decay=0.5): |
|---|
| 19 | _position(0.0), _velocity(0.0), _elapsedS(0.0), _decay(decay) |
|---|
| 20 | {} |
|---|
| 21 | |
|---|
| 22 | void spin(float velocity) { |
|---|
| 23 | // Start the fidget spinner moving at the specified velocity (in pixels/second). |
|---|
| 24 | // Over time the spinner will slow down based on its decay value. |
|---|
| 25 | _velocity = velocity; |
|---|
| 26 | _elapsedS = 0.0; // Reset elapsed time to start the decay from the beginning. |
|---|
| 27 | } |
|---|
| 28 | |
|---|
| 29 | float getPosition(float deltaS) { |
|---|
| 30 | // Get the fidget spinner's current position after moving for the specified number |
|---|
| 31 | // of milliseconds. Returns a continuous value in the range 0...<10. |
|---|
| 32 | _elapsedS += deltaS; |
|---|
| 33 | // Compute current velocity based on exponential decay of initial |
|---|
| 34 | // velocity over the elapsed time (this causes the spinner to |
|---|
| 35 | // gradually slow down and mimics the effects of friction). |
|---|
| 36 | float currentVelocity = _velocity*pow(_decay, _elapsedS); |
|---|
| 37 | // Now move the position based on the current velocity. |
|---|
| 38 | _position += currentVelocity*deltaS; |
|---|
| 39 | // Finally make sure position is constrained within 0...<10 range. |
|---|
| 40 | _position = fmod(_position, 10.0); |
|---|
| 41 | if (_position < 0.0) { |
|---|
| 42 | // Ensure position is never negative by wrapping back to the |
|---|
| 43 | // same pixel position in a positive location. |
|---|
| 44 | _position += 10.0; |
|---|
| 45 | } |
|---|
| 46 | return _position; |
|---|
| 47 | } |
|---|
| 48 | |
|---|
| 49 | private: |
|---|
| 50 | float _position; |
|---|
| 51 | float _velocity; |
|---|
| 52 | float _elapsedS; |
|---|
| 53 | float _decay; |
|---|
| 54 | }; |
|---|
| 55 | |
|---|
| 56 | #endif |
|---|