Skip to content

Instantly share code, notes, and snippets.

@SharpCoder
Created April 16, 2016 21:45
Show Gist options
  • Select an option

  • Save SharpCoder/e41c8058cb899bb6d21f4b024a788941 to your computer and use it in GitHub Desktop.

Select an option

Save SharpCoder/e41c8058cb899bb6d21f4b024a788941 to your computer and use it in GitHub Desktop.
class Drawable
constructor: (options) ->
if !options? then options = {}
# Destructuring to assign properties based on obj
{
@name
@x
@y
@vx = 0
@vy = 0
@scaleX = 1.0
@scaleY = 1.0
@base_img_src
@animation_name
@animation_interval
} = options
@animation_start
@animation_index = 0
# Load the image object if src was passed in
if @base_img_src?
@img = Assets.get(@base_img_src)
@img_w = @img.width
@img_h = @img.height
setAnimation: (animation_name, animation_interval) ->
@animation_name = animation_name
@animation_index = 0
@animation_start = new Date().getTime()
if animation_interval?
@animation_interval = animation_interval
else
@animation_interval = 100
getCurrentImage: ->
img_src = @base_img_src + "_" + @animation_name + "_" + @animation_index
keydown: (evt) ->
console.log(evt)
keyup: (evt) ->
console.log(evt)
draw: (ctx, e) ->
if ctx? and @img?
ctx.drawImage(
@img,
0, # source offset
0, # source offset
@img.width, # source width
@img.height, # source height
@x, # destination x
@y, # destination y
@img.width*@scaleX, # destination width
@img.height*@scaleY # destination height
)
update: (canvas, e) ->
# Basic vectors
if @vx? and @x
@x += @vx
if @vy? and @y
@y += @vy
# Check for animation changes
if @animation_name?
if !@animation_start? then @animation_start = new Date().getTime()
cur = new Date().getTime()
if (cur - @animation_start) > @animation_interval
@animation_index++
@animation_start = cur
img_src = @getCurrentImage()
if Assets.exists(img_src)
@img = Assets.get(img_src)
else
@animation_index = 0
@img = Assets.get(@getCurrentImage())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment