SimpleTweens.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import Easing from "./Easings"
  2. import * as RE from 'rogue-engine';
  3. export class TweenManager {
  4. activeTweens = []
  5. elapsed = 0
  6. awake() {
  7. }
  8. start() {
  9. this.elapsed = 0
  10. }
  11. update() {
  12. this.elapsed += RE.Runtime.deltaTime
  13. let tweensToRemove = []
  14. this.activeTweens.forEach(tween => {
  15. if(tween.update(this.elapsed)) {
  16. tweensToRemove.push(tween)
  17. }
  18. })
  19. for(let i = tweensToRemove.length - 1; i >= 0; i--) {
  20. this.remove(tweensToRemove[i])
  21. }
  22. }
  23. add(simpleTween) {
  24. this.activeTweens.push(simpleTween)
  25. simpleTween.start(this.elapsed)
  26. }
  27. remove(simpleTween) {
  28. delete this.activeTweens[this.activeTweens.indexOf(simpleTween)]
  29. }
  30. }
  31. export class SimpleTween {
  32. constructor(initialObject, targetProperties, duration = 1000, easingFunction = Easing.Linear.EaseNone, onComplete = () => {}) {
  33. this.initialObject = initialObject
  34. this.targetProperties = targetProperties
  35. this.duration = duration / 1000
  36. this.easingFunction = easingFunction
  37. this.onComplete = onComplete
  38. }
  39. start(elapsed) {
  40. this.copy = {}
  41. for(let key in this.targetProperties) {
  42. this.copy[key] = this.initialObject[key]
  43. }
  44. this.begin = elapsed
  45. }
  46. update(elapsed) {
  47. if(elapsed >= this.begin + this.duration) {
  48. for(let key in this.targetProperties) {
  49. this.initialObject[key] = this.targetProperties[key]
  50. }
  51. this.onComplete()
  52. return true
  53. }
  54. let delta = (elapsed - this.begin) / this.duration
  55. for(let key in this.targetProperties) {
  56. this.initialObject[key] = (this.targetProperties[key] - this.copy[key]) * this.easingFunction(delta) + this.copy[key]
  57. }
  58. return false
  59. }
  60. }