Advertisement
Zac_McDonald

Unity C# - Rounding to intervals

Mar 24th, 2017
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. public class IntervalClamp : MonoBehaviour
  2.     {
  3.  
  4.         #region Public Fields
  5.         public float speed;                 // For moving the object
  6.         public float interval = 0.0625f;    // [1/16]
  7.         #endregion
  8.  
  9.         #region Private Fields
  10.         private Vector3 actualPosition;     // Where the object is in 3D space (unlocked)
  11.         #endregion
  12.  
  13.         #region Unity Methods
  14.         protected void Start ()
  15.         {
  16.             actualPosition = transform.position;
  17.         }
  18.  
  19.         protected void Update ()
  20.         {
  21.             // Moving the objects actual position along the X-Axis : All movement should be to the 'actual position'
  22.             actualPosition = new Vector3(actualPosition.x + speed * Time.deltaTime, actualPosition.y, actualPosition.z);
  23.  
  24.             Vector3 lockedPosition = actualPosition;                            // Position when unlocked to interval
  25.             lockedPosition.x = RoundToInterval(lockedPosition.x, interval);     // Locking the x-coordinate to the interval : Run this on all coords for all to be locked
  26.  
  27.             transform.position = lockedPosition;                                // Setting the Transform to the locked position
  28.         }
  29.         #endregion
  30.  
  31.         #region Public Methods
  32.         #endregion
  33.  
  34.         #region Private Methods
  35.         private float RoundToInterval (float value, float interval)             // Will round a number to the nearest interval
  36.         {
  37.             int numberOfIntervals = Mathf.RoundToInt(value / interval);
  38.             float roundedValue = numberOfIntervals * interval;
  39.             return roundedValue;
  40.         }
  41.  
  42.         private float RoundUpToInterval(float value, float interval)            // Will round a number up to the nearest interval
  43.         {
  44.             int numberOfIntervals = Mathf.RoundToInt((value + interval / 2) / interval);
  45.             float roundedValue = numberOfIntervals * interval;
  46.             return roundedValue;
  47.         }
  48.  
  49.         private float RoundDownToInterval(float value, float interval)          // Will round a number down to the nearest interval
  50.         {
  51.             int numberOfIntervals = Mathf.RoundToInt((value - interval/2) / interval);
  52.             float roundedValue = numberOfIntervals * interval;
  53.             return roundedValue;
  54.         }
  55.         #endregion
  56.  
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement