Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /// <summary>
- /// This class moves an object, usually a light, in a random pattern to
- /// simulate the movement of flames inside a fire and make the lighting and
- /// shadowing more natural.
- /// </summary>
- public class FireLightMovement : MonoBehaviour {
- [Tooltip ( "The maximum amplitude in each principal direction." )]
- public Vector3 amplitude = Vector3.one * 0.1f;
- [Tooltip ( "The base frequency for the movement." )]
- public float frequency = 0.1f;
- [Tooltip ( "The deviation that is allowed for each movement. Ranges from 0 to 0.95 of the frequency." )]
- [Range ( 0f, 0.95f )]
- public float frequencyDeviation = 0.5f;
- private Vector3 _initialPosition = Vector3.zero; // Stores the initial position of the object.
- private Vector3 _randomOffset = Vector3.one; // The randomized offset from the position.
- private Vector3 _targetPosition = Vector3.zero; // The current target position.
- private Vector3 _lastPosition = Vector3.zero; // The last taret position.
- private float _cooldown = 0f;
- private float _frequencyDeviationOffset = 0f;
- private float _travel = 0f;
- void Start() {
- // We need to store the initial position to not wander off.
- _initialPosition = _lastPosition = _targetPosition = transform.position;
- }
- void Update() {
- // The calculations for a new offset are only done when the cooldown is over.
- if ( _cooldown <= 0f ) {
- // The offset is a random value inside a unit sphere scaled by the amplitude.
- _randomOffset = Random.insideUnitSphere;
- _randomOffset.Scale ( amplitude );
- // The target position is calculated from the offset and the initial position.
- _targetPosition = _initialPosition + _randomOffset;
- // Stored for reference later.
- _lastPosition = transform.position;
- // The frequency deviation is calculated to make the movement more random.
- _frequencyDeviationOffset = Random.Range ( -1.0f, 1.0f ) * ( frequencyDeviation * frequency );
- // The cooldown needs to respect the calculated offset.
- _cooldown = frequency + _frequencyDeviationOffset;
- }
- // The travel describes which percentage of the cooldown is already over.
- if ( _cooldown < Time.deltaTime ) {
- // If the cooldown is shorter than one frame it is set to zero.
- _travel = 0f;
- } else {
- _travel = _cooldown / ( frequency + _frequencyDeviationOffset );
- }
- /*
- * The object is moved from the last position to the new target position by
- * a percentage of the distance that is proportional to the remaining cooldown.
- */
- transform.position = _lastPosition + ( _targetPosition - _lastPosition ) * Mathf.Clamp01 ( 1f - _travel );
- _cooldown -= Time.deltaTime;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement