Created
April 22, 2020 16:43
-
-
Save Manamongods/defaef69d1640e236de6465d0657c9ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Steffen Vetne made this | |
//Creative Commons 0 | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
[ExecuteInEditMode] | |
public class Swayer : MonoBehaviour | |
{ | |
//Fields | |
public Vector3 rotationOffset = Vector3.zero; | |
public Vector3 axis = Vector3.right; | |
[Header("Animation")] | |
public AnimationCurve swayAnimation = null; | |
public float swayOffset = 0; | |
public float swayMultiplier = 20; | |
public float swayFinalOffset = 0; | |
[Header("Time")] | |
public Vector2 randomStartTime = new Vector2(0, 10); | |
public float rateMultiplier = 1; | |
public Vector2 randomRate = new Vector2(1, 2); | |
private float t; | |
private float rate; | |
//Lifecycle | |
#if UNITY_EDITOR | |
private void OnValidate() | |
{ | |
#region Default Sway Curve | |
if (swayAnimation == null) | |
{ | |
var keys = new Keyframe[3]; | |
var keyframe = new Keyframe(0, -1) { inTangent = 0, outTangent = 0 }; | |
keys[0] = keyframe; | |
keyframe.time = 1; | |
keyframe.value = 1; | |
keys[1] = keyframe; | |
keyframe.time = 2; | |
keyframe.value = -1; | |
keys[2] = keyframe; | |
swayAnimation = new AnimationCurve() { keys = keys }; | |
} | |
#endregion | |
swayAnimation.postWrapMode = swayAnimation.preWrapMode = WrapMode.Loop; | |
//OnEnable(); | |
} | |
private void OnDrawGizmosSelected() | |
{ | |
float size = UnityEditor.HandleUtility.GetHandleSize(transform.position) * 0.75f; | |
Vector3 axis = this.axis; | |
if (transform.parent != null) | |
axis = transform.parent.TransformDirection(axis); | |
Gizmos.DrawRay(transform.position, axis * size); | |
} | |
#endif | |
private void OnEnable() | |
{ | |
rate = Random.Range(randomRate.x, randomRate.y); | |
t = Random.Range(randomStartTime.x, randomStartTime.y); | |
} | |
private void Update() | |
{ | |
t += rateMultiplier * rate * Time.deltaTime; | |
float a = (swayAnimation.Evaluate(t) + swayOffset) * swayMultiplier + swayFinalOffset; | |
transform.localRotation = Quaternion.AngleAxis(a, axis) * Quaternion.Euler(rotationOffset); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment