Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // NOTE: Also needs the IntervalClampHelper Script: https://pastebin.com/dPUKwRfs
- [RequireComponent(typeof(IntervalClampHelper))]
- public class IntervalClampUpdate : MonoBehaviour
- {
- // Needs to be set to run after the default time: Edit/Project Settings/Script Execution Order
- #region Public Fields
- //[HideInInspector] // Uncomment if you don't want to see the current position in the inspector
- public Vector3 actualPosition; // Used by the helper to carry our actual position across frames
- public float interval = 0.0625f; // [1/16]
- #endregion
- #region Private Fields
- #endregion
- #region Unity Methods
- protected void Start ()
- {
- // Set the inital position
- actualPosition = transform.position;
- }
- protected void LateUpdate ()
- {
- // This runs at the end of a frame, before rendering.
- // Here we store the current position so we can carry it to
- // the following frame. We then clamp the position as per normal.
- actualPosition = transform.position;
- Vector3 lockedPosition = actualPosition;
- lockedPosition.x = RoundToInterval(lockedPosition.x, interval);
- lockedPosition.y = RoundToInterval(lockedPosition.y, interval);
- lockedPosition.z = RoundToInterval(lockedPosition.z, interval);
- transform.position = lockedPosition;
- }
- #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