From 4fa246628bd9e5911ae998162f0bdc724cc739d2 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Wed, 6 Jan 2016 08:52:06 +0100 Subject: Add entity rendering --- src/view/MapView.coffee | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) (limited to 'src/view') diff --git a/src/view/MapView.coffee b/src/view/MapView.coffee index cafc0aa..e051d48 100644 --- a/src/view/MapView.coffee +++ b/src/view/MapView.coffee @@ -1,6 +1,5 @@ 'use strict' -_ = require 'lodash' util = require '../util' @@ -19,12 +18,20 @@ loadImage = (url) -> loadImages = (imgs) -> util.mapPromises(_.mapValues imgs, loadImage) -loadTiles = (tileDef) -> - loadImages(_.mapValues tileDef, (t) -> "resources/sprite/tile/#{t.file}.png") +loadTiles = (tiles) -> + loadImages(_.mapValues tiles, (t) -> "resources/sprite/tile/#{t.file}.png") + +loadEntities = (entities) -> + p = {} + for e in entities + do (e) -> + p[e.entity.name] = loadImage "resources/sprite/entity/#{e.entity.name}.png" + + util.mapPromises p class MapView - constructor: (@map) -> + constructor: (@map, @entities) -> @redrawPending = false @canvas = document.createElement 'canvas' @@ -36,22 +43,38 @@ class MapView window.addEventListener 'resize', @setSize @setSize() - @ready = loadTiles(@map.tiles).then (tiles) => + tilesReady = loadTiles(@map.tiles).then (tiles) => @tiles = tiles + + entitiesReady = loadEntities(_.values @entities).then (entities) => + @entitySprites = entities + + tilesReady.then(entitiesReady).then => @redraw() return drawTile: (x, y, tile) => return unless tile - @ctx.drawImage(tile, x, y) + @ctx.drawImage tile, x, y + + drawEntity: (e) => + sprite = @entitySprites[e.entity.name] + return unless sprite + + @ctx.drawImage( + sprite, + e.direction*tileSize, 0, + tileSize, tileSize, + e.position.x*tileSize, e.position.y*tileSize, + tileSize, tileSize) draw: => @redrawPending = false @ctx.clearRect 0, 0, @canvas.width, @canvas.height - return unless @tiles + return unless @tiles and @entitySprites for layer in @map.layers y = 0 @@ -65,6 +88,9 @@ class MapView y += tileSize + for e in _.values @entities + @drawEntity e + redraw: => unless @redrawPending @redrawPending = true -- cgit v1.2.3