engine/drawables/AnimatedImage.bs

' @module BGE
namespace BGE

  class AnimatedImage extends Image
    ' -------------Only To Be Changed For Animation---------------
    ' The following values should only be changed if the image is a spritesheet that needs to be animated.
    ' The spritesheet can have any assortment of multiple columns and rows.

    ' The current index of image - this would not normally be changed manually, but if you wanted to stop on a specific image in the spritesheet this could be set.
    index as integer = 0
    ' The time in milliseconds for a single cycle through the animation to play.
    animationDurationMs as float = 0
    ' The name of the tween to use for choosing the next image
    animationTween as string = "LinearTween"


    ' -------------Never To Be Manually Changed-----------------
    ' These values should never need to be manually changed.
    protected regions as object = invalid
    private animationTimer = new GameTimer()
    private tweensReference = BGE.Tweens.GetTweens()

    function new(owner as GameEntity, canvasBitmap as object, regions as object, args = {} as object)
      super(owner, canvasBitmap, invalid, args)
      m.regions = regions
      m.append(args)
    end function


    override function draw(additionalRotation = 0 as float)
      if m.enabled
        if m.animationDurationMs > 0 and not m.owner.game.isPaused()
          m.index = m.getCellDrawIndex()
        end if
        totalRotation = additionalRotation + m.rotation
        if m.index >= 0 and m.index < m.regions.Count()
          m.region = m.regions[m.index]
          m.drawRegionToCanvas(m.region, totalRotation)
          m.width = m.region.getWidth()
          m.height = m.region.getHeight()
        end if
      end if
    end function

    protected function getCellDrawIndex() as integer
      frame_count = m.regions.Count()
      currentTimeMs = m.animationTimer.TotalMilliseconds()
      if currentTimeMs > m.animationDurationMs
        currentTimeMs -= m.animationDurationMs
        m.animationTimer.RemoveTime(m.animationDurationMs)
      end if
      index = m.tweensReference[m.animationTween](0, frame_count, currentTimeMs, m.animationDurationMs)
      if index > frame_count - 1
        index = frame_count - 1
      else if m.index < 0
        index = 0
      end if
      return index
    end function

    override function onResume(pausedTime as integer)
      m.animationTimer.RemoveTime(pausedTime)
    end function
  end class
end namespace