Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@ChrisGermano

This comment has been minimized.

Show comment
Hide comment
Owner

ChrisGermano commented Aug 31, 2017

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