diff options
Diffstat (limited to 'src/view')
-rw-r--r-- | src/view/entity.ts | 33 | ||||
-rw-r--r-- | src/view/util/image.ts | 6 |
2 files changed, 24 insertions, 15 deletions
diff --git a/src/view/entity.ts b/src/view/entity.ts index b59bf92..7600826 100644 --- a/src/view/entity.ts +++ b/src/view/entity.ts @@ -8,21 +8,28 @@ import { vec2 } from 'gl-matrix'; export async function loadEntity( r: Renderer, data: EntityData, -): Promise<SpriteView> { +): Promise<SpriteView[]> { const tile = await loadImage(`resources/sprite/entity/${data.sprite}.png`); - const [texture, size, coords] = mkTexture(r, tile); - const offset = vec2.mul(vec2.create(), data.anchor, size); - r.snapToGrid(offset, offset); + const sprites: SpriteView[] = []; - const anchorCoords: SpriteCoords = [ - coords[0] - offset[0], - coords[1] - offset[1], - coords[2] - offset[0], - coords[3] - offset[1], - ]; + for (let frame = 0; frame < data.frames; frame++) { + const [texture, size, coords] = mkTexture(r, tile, frame, data.frames); - const builder = new SpriteViewBuilder(r, texture); - builder.addSprite(anchorCoords, [0, 0, 1, 1]); - return builder.build(); + const offset = vec2.mul(vec2.create(), data.anchor, size); + r.snapToGrid(offset, offset); + + const anchorCoords: SpriteCoords = [ + coords[0] - offset[0], + coords[1] - offset[1], + coords[2] - offset[0], + coords[3] - offset[1], + ]; + + const builder = new SpriteViewBuilder(r, texture); + builder.addSprite(anchorCoords, [0, 0, 1, 1]); + sprites.push(builder.build()); + } + + return sprites; } diff --git a/src/view/util/image.ts b/src/view/util/image.ts index e01246c..7baeccc 100644 --- a/src/view/util/image.ts +++ b/src/view/util/image.ts @@ -14,13 +14,15 @@ export function loadImage(url: string): Promise<HTMLImageElement> { export function mkTexture( r: Renderer, src: HTMLCanvasElement|HTMLImageElement, + frame: number = 0, + total: number = 1, ): [WebGLTexture, [number, number], SpriteCoords] { const gl = r.getContext(); const texture = gl.createTexture(); if (!texture) throw new Error('unable to create texture'); - const w = src.width, h = src.height; + const w = src.width, h = src.height / total; const w2 = nextPowerOf2(w), h2 = nextPowerOf2(h); const canvas = document.createElement('canvas'); @@ -28,7 +30,7 @@ export function mkTexture( canvas.height = h2; const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; - ctx.drawImage(src, 0, 0); + ctx.drawImage(src, 0, frame * h, w, h, 0, 0, w, h); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvas); |