Procedural animation

IntermediateProgrammer

Procedural animation is an alternative method of animation. Instead of creating animations yourself, you can use engine components to animate 3D models at runtime.

In some cases, this creates more effective and efficient animations. For example, imagine a shrink effect that happens when the player shoots a monster with a shrink weapon. Instead of creating a complex shrinking animation, you can access the entity TransformComponent and simply scale the enemy down to the required size.

You can access multiple components to animate your models at runtime, including:

Code sample

  1. public class AnimationScript : StartupScript
  2. {
  3. public override void Start()
  4. {
  5. // Create an AnimationClip. Make sure you set its duration properly.
  6. var animationClip = new AnimationClip { Duration = TimeSpan.FromSeconds(1) };
  7. // Add a curves specifying the path to the transformation property.
  8. // - You can index components using a special syntax to their key.
  9. // - Properties can be qualified with a type name in parenthesis.
  10. // - If a type isn't serializable, its fully qualified name must be used.
  11. animationClip.AddCurve("[TransformComponent.Key].Rotation", CreateRotationCurve());
  12. // Optional: pack all animation channels into an optimized interleaved format.
  13. animationClip.Optimize();
  14. // Add an AnimationComponent to the current entity and register our custom clip.
  15. const string animationName = "MyCustomAnimation";
  16. var animationComponent = Entity.GetOrCreate<AnimationComponent>();
  17. animationComponent.Animations.Add(animationName, animationClip);
  18. // Play the animation right away and loop it.
  19. var playingAnimation = animationComponent.Play(animationName);
  20. playingAnimation.RepeatMode = AnimationRepeatMode.LoopInfinite;
  21. playingAnimation.TimeFactor = 0.1f; // slow down
  22. playingAnimation.CurrentTime = TimeSpan.FromSeconds(0.6f); // start at different time
  23. }
  24. // Set custom linear rotation curve.
  25. private AnimationCurve CreateRotationCurve()
  26. {
  27. return new AnimationCurve<Quaternion>
  28. {
  29. InterpolationType = AnimationCurveInterpolationType.Linear,
  30. KeyFrames =
  31. {
  32. CreateKeyFrame(0.00f, Quaternion.RotationX(0)),
  33. CreateKeyFrame(0.25f, Quaternion.RotationX(MathUtil.PiOverTwo)),
  34. CreateKeyFrame(0.50f, Quaternion.RotationX(MathUtil.Pi)),
  35. CreateKeyFrame(0.75f, Quaternion.RotationX(-MathUtil.PiOverTwo)),
  36. CreateKeyFrame(1.00f, Quaternion.RotationX(MathUtil.TwoPi))
  37. }
  38. };
  39. }
  40. private static KeyFrameData<T> CreateKeyFrame<T>(float keyTime, T value)
  41. {
  42. return new KeyFrameData<T>((CompressedTimeSpan)TimeSpan.FromSeconds(keyTime), value);
  43. }
  44. }

See also