Skip to content

Instantly share code, notes, and snippets.

@ChrisGermano
Last active August 31, 2017 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisGermano/d48a83d0c270cd6b580d3f4a53e3bb1a to your computer and use it in GitHub Desktop.
Save ChrisGermano/d48a83d0c270cd6b580d3f4a53e3bb1a to your computer and use it in GitHub Desktop.
Simple Data-Driven Weapon Animation in Unity 3D
//This is to be used within an existing C# file
//Either assign these in the GUI inspector or elsewhere in your code
public GameObject weapon; //The object to be animated
public Vector3[] positions; //The positions the object will animate through (local position)
public Vector3[] rotations; //The Euler angles of the object to be animated (local Euler angles)
public float[] durations; //The number of seconds the object takes to reach each position
public float variance; //The amount of variety in positions between attacks (0f for identical animations every time)
//To animate, call StartCoroutine(Attack())
IEnumerator Attack() {
for (int i = 0; i < durations.Length; i++) {
float elapsed = 0f;
float duration = durations[i];
Vector3 startPos = positions[i];
Vector3 startRot = rotations[i];
bool isEnd = i == positions.Length-1;
Vector3 endPos = isEnd ? positions[0] : positions[i+1] * (1f + Random.Range(-variance, variance));
Vector3 endRot = isEnd ? rotations[0] : rotations[i+1] * (1f + Random.Range(-variance,variance));
while (elapsed < duration) {
weapon.transform.localPosition = Vector3.Lerp(startPos, endPos, elapsed/duration);
weapon.transform.localEulerAngles = Vector3.Lerp(startRot, endRot, elapsed/duration);
elapsed += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
}
}
@ChrisGermano
Copy link
Author

@ChrisGermano
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment