Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class IntervalClamp : MonoBehaviour
- {
- #region Public Fields
- public float speed; // For moving the object
- public float interval = 0.0625f; // [1/16]
- #endregion
- #region Private Fields
- private Vector3 actualPosition; // Where the object is in 3D space (unlocked)
- #endregion
- #region Unity Methods
- protected void Start ()
- {
- actualPosition = transform.position;
- }
- protected void Update ()
- {
- // Moving the objects actual position along the X-Axis : All movement should be to the 'actual position'
- actualPosition = new Vector3(actualPosition.x + speed * Time.deltaTime, actualPosition.y, actualPosition.z);
- Vector3 lockedPosition = actualPosition; // Position when unlocked to interval
- lockedPosition.x = RoundToInterval(lockedPosition.x, interval); // Locking the x-coordinate to the interval : Run this on all coords for all to be locked
- transform.position = lockedPosition; // Setting the Transform to the locked position
- }
- #endregion
- #region Public Methods
- #endregion
- #region Private Methods
- private float RoundToInterval (float value, float interval) // Will round a number to the nearest interval
- {
- int numberOfIntervals = Mathf.RoundToInt(value / interval);
- float roundedValue = numberOfIntervals * interval;
- return roundedValue;
- }
- private float RoundUpToInterval(float value, float interval) // Will round a number up to the nearest interval
- {
- int numberOfIntervals = Mathf.RoundToInt((value + interval / 2) / interval);
- float roundedValue = numberOfIntervals * interval;
- return roundedValue;
- }
- private float RoundDownToInterval(float value, float interval) // Will round a number down to the nearest interval
- {
- int numberOfIntervals = Mathf.RoundToInt((value - interval/2) / interval);
- float roundedValue = numberOfIntervals * interval;
- return roundedValue;
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement