42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
|
import { Juego } from "./main"
|
||
|
|
||
|
// Sprites are image assets that have a grid of tiles to animate
|
||
|
export function loadSprite(
|
||
|
img: HTMLImageElement,
|
||
|
// The size of each tile
|
||
|
width: number, height: number,
|
||
|
// Calculates the size of the sprite when rendering
|
||
|
getHeight: (juego: Juego<any>) => number,
|
||
|
) {
|
||
|
|
||
|
const aspect = width / height
|
||
|
const rowSize = Math.floor(img.width / width)
|
||
|
if (img.width / width !== rowSize) {
|
||
|
console.warn(`The sprite grid for ${img.src} has extra space after rows, are you sure the width/height of each tile is right?`)
|
||
|
}
|
||
|
|
||
|
function getWidth(juego: Juego<any>) {
|
||
|
return getHeight(juego) * aspect
|
||
|
}
|
||
|
|
||
|
function draw(juego: Juego<any>, x: number, y: number, spriteIndex: number) {
|
||
|
const drawHeight = getHeight(juego)
|
||
|
const drawWidth = getWidth(juego)
|
||
|
const tileX = spriteIndex % rowSize
|
||
|
const tileY = Math.floor(spriteIndex / rowSize)
|
||
|
juego.ctx.drawImage(
|
||
|
img,
|
||
|
tileX * width,
|
||
|
tileY * height,
|
||
|
width,
|
||
|
height,
|
||
|
x,
|
||
|
y,
|
||
|
drawWidth,
|
||
|
drawHeight,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
return { getWidth, getHeight, draw, width, height }
|
||
|
}
|