1
0

RotationVisualizerSystem.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using Content.Shared.Rotation;
  2. using Robust.Client.Animations;
  3. using Robust.Client.GameObjects;
  4. using Robust.Shared.Animations;
  5. namespace Content.Client.Rotation;
  6. public sealed class RotationVisualizerSystem : SharedRotationVisualsSystem
  7. {
  8. [Dependency] private readonly AppearanceSystem _appearance = default!;
  9. [Dependency] private readonly AnimationPlayerSystem _animation = default!;
  10. public override void Initialize()
  11. {
  12. base.Initialize();
  13. SubscribeLocalEvent<RotationVisualsComponent, AppearanceChangeEvent>(OnAppearanceChange);
  14. }
  15. private void OnAppearanceChange(EntityUid uid, RotationVisualsComponent component, ref AppearanceChangeEvent args)
  16. {
  17. if (args.Sprite == null)
  18. return;
  19. if (!_appearance.TryGetData<RotationState>(uid, RotationVisuals.RotationState, out var state, args.Component))
  20. return;
  21. switch (state)
  22. {
  23. case RotationState.Vertical:
  24. AnimateSpriteRotation(uid, args.Sprite, component.VerticalRotation, component.AnimationTime);
  25. break;
  26. case RotationState.Horizontal:
  27. AnimateSpriteRotation(uid, args.Sprite, component.HorizontalRotation, component.AnimationTime);
  28. break;
  29. }
  30. }
  31. /// <summary>
  32. /// Rotates a sprite between two animated keyframes given a certain time.
  33. /// </summary>
  34. public void AnimateSpriteRotation(EntityUid uid, SpriteComponent spriteComp, Angle rotation, float animationTime)
  35. {
  36. if (spriteComp.Rotation.Equals(rotation))
  37. {
  38. return;
  39. }
  40. var animationComp = EnsureComp<AnimationPlayerComponent>(uid);
  41. const string animationKey = "rotate";
  42. // Stop the current rotate animation and then start a new one
  43. if (_animation.HasRunningAnimation(animationComp, animationKey))
  44. {
  45. _animation.Stop(animationComp, animationKey);
  46. }
  47. var animation = new Animation
  48. {
  49. Length = TimeSpan.FromSeconds(animationTime),
  50. AnimationTracks =
  51. {
  52. new AnimationTrackComponentProperty
  53. {
  54. ComponentType = typeof(SpriteComponent),
  55. Property = nameof(SpriteComponent.Rotation),
  56. InterpolationMode = AnimationInterpolationMode.Linear,
  57. KeyFrames =
  58. {
  59. new AnimationTrackProperty.KeyFrame(spriteComp.Rotation, 0),
  60. new AnimationTrackProperty.KeyFrame(rotation, animationTime)
  61. }
  62. }
  63. }
  64. };
  65. _animation.Play((uid, animationComp), animation, animationKey);
  66. }
  67. }