Skip to content

Commit

Permalink
Refactoring drawing of sprites
Browse files Browse the repository at this point in the history
  • Loading branch information
rbgrouleff committed Jan 9, 2012
1 parent 2250e31 commit e4a6b4e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
7 changes: 7 additions & 0 deletions lib/scene.coffee
Expand Up @@ -2,6 +2,13 @@ module.exports = class Scene
constructor: (@screen, @context) ->
@sprites = []

addSprite: (sprite) ->
@sprites.push sprite

redraw: ->
@screen.clear()
sprite.draw @context for sprite in @sprites

draw: (image, x, y) ->
@context.drawImage image, x, y

Expand Down
14 changes: 11 additions & 3 deletions lib/sprite.coffee
Expand Up @@ -8,6 +8,14 @@ module.exports = class Sprite
else
@initSprite(image)

setPosition: (x,y) ->
@x = x
@y = y

move: (x,y) ->
@x = @x + x
@y = @y + y

initSprite: (image) ->
@img = document.createElement 'canvas'
@img.width = @width
Expand All @@ -16,9 +24,9 @@ module.exports = class Sprite
ctx.drawImage image, @offset_x, @offset_y, @width, @height, 0, 0, @width, @height
@drawCallback?()

draw: (scene, x, y) ->
draw: (context) ->
if @image_complete
scene.draw @img, x, y
context.drawImage @img, @x, @y
else
@drawCallback = =>
scene.draw @img, x, y
context.drawImage @img, @x, @y
12 changes: 7 additions & 5 deletions test/test.coffee
Expand Up @@ -8,9 +8,12 @@ img = new Image
img.src = '/images/simple_sprite.png'
window.sprite = new Squash.Sprite img, 0, 0, 20, 20

@x = 90
@x = 0
@y = 90
sprite.draw scene, @x, @y

sprite.setPosition(@x, @y)
scene.addSprite sprite
scene.redraw()

window.timer = new Squash.Timer

Expand All @@ -21,10 +24,9 @@ timer.registerCallback (timeSinceLastTick) =>
console.log "FPS: #{@ticks}"
@ms = 0
@ticks = 0
scene.clear()
@x = @x + 10
sprite.draw scene, @x, @y
sprite.move 10, 0
else
@ms += timeSinceLastTick
@ticks += 1
scene.redraw()
timer.start()

0 comments on commit e4a6b4e

Please sign in to comment.