Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Original script by Joyce[MinionsArt]
- using OhiraKyou;
- using UnityEngine;
- public class LiquidWobble : MonoBehaviour {
- [Header("Setup")]
- [SerializeField]
- private Transform _velocityReferenceTransform;
- public Transform VelocityReferenceTransform {
- get { return _velocityReferenceTransform; }
- set { _velocityReferenceTransform = value; }
- }
- [SerializeField]
- private Renderer _targetRenderer;
- public Renderer TargetRenderer {
- get { return _targetRenderer; }
- set { _targetRenderer = value; }
- }
- [Header("Wobble")]
- [SerializeField]
- private float _maxWobble = 0.05f;
- public float MaxWobble {
- get { return _maxWobble; }
- set { _maxWobble = value; }
- }
- [SerializeField]
- private float _wobbleDuration = 1.5f;
- public float WobbleDuration {
- get { return _wobbleDuration; }
- set { _wobbleDuration = value; }
- }
- [SerializeField]
- private float _recoverySpeed = 1f;
- public float RecoverySpeed {
- get { return _recoverySpeed; }
- set { _recoverySpeed = value; }
- }
- private float _wobbleAmountX;
- private float _wobbleAmountZ;
- private float _wobbleAmountToAddX;
- private float _wobbleAmountToAddZ;
- private float _pulse;
- private float _currentTime = 0.5f;
- private Vector3 _lastPosition;
- private Vector3 _velocity;
- private void Update () {
- if (_targetRenderer) {
- // Decrease wobble over time
- _wobbleAmountToAddX = Mathf.Lerp(_wobbleAmountToAddX, 0f, Time.deltaTime * RecoverySpeed);
- _wobbleAmountToAddZ = Mathf.Lerp(_wobbleAmountToAddZ, 0f, Time.deltaTime * RecoverySpeed);
- // Calculate the current wobble time percent
- _currentTime = CustomMath.GetWrappedSeconds(_currentTime, WobbleDuration);
- float wobblePercent = _currentTime / WobbleDuration;
- // The result of 0 and 360 degrees should be identical, and there are 2pi radians in 360 degrees
- float wobbleRadians = wobblePercent * 2f * Mathf.PI;
- // Make a sine wave of the decreasing wobble
- _wobbleAmountX = _wobbleAmountToAddX * Mathf.Sin(wobbleRadians);
- _wobbleAmountZ = _wobbleAmountToAddZ * Mathf.Sin(wobbleRadians);
- // Send it to the shader
- _targetRenderer.material.SetFloat("_WobbleX", _wobbleAmountX);
- _targetRenderer.material.SetFloat("_WobbleZ", _wobbleAmountZ);
- // Calculate velocity
- _velocity = (_lastPosition - _velocityReferenceTransform.position) / Time.deltaTime;
- // Add clamped velocity to wobble
- _wobbleAmountToAddX += Mathf.Clamp(_velocity.x * MaxWobble, -MaxWobble, MaxWobble);
- _wobbleAmountToAddZ += Mathf.Clamp(_velocity.z * MaxWobble, -MaxWobble, MaxWobble);
- // Remember position for next frame
- _lastPosition = _velocityReferenceTransform.position;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment