salva-la-costanera/src/sprite.ts

81 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-06-30 23:16:45 +00:00
import { Juego } from "./main";
2021-06-28 18:01:45 +00:00
export type Sprite = {
2021-06-30 23:16:45 +00:00
getWidth: (juego: Juego<any>) => number;
getHeight: (juego: Juego<any>) => number;
draw: (
juego: Juego<any>,
x: number,
y: number,
spriteIndex?: number,
flipped?: boolean
) => void;
width: number;
height: number;
};
2021-06-28 18:01:45 +00:00
// Sprites are image assets that have a grid of tiles to animate
export function loadSprite(
2021-06-30 23:16:45 +00:00
img: HTMLImageElement,
// The size of each tile
width: number,
height: number,
// Calculates the size of the sprite when rendering
getHeight: (juego: Juego<any>) => number
): Sprite {
2021-06-30 23:16:45 +00:00
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?`
);
}
2021-06-28 18:01:45 +00:00
2021-06-30 23:16:45 +00:00
function getWidth(juego: Juego<any>) {
return getHeight(juego) * aspect;
}
2021-06-28 18:01:45 +00:00
2021-06-30 23:16:45 +00:00
function draw(
juego: Juego<any>,
x: number,
y: number,
spriteIndex = 0,
flipped = false
) {
const drawHeight = getHeight(juego);
const drawWidth = getWidth(juego);
const tileX = spriteIndex % rowSize;
const tileY = Math.floor(spriteIndex / rowSize);
if (flipped) {
juego.ctx.save();
juego.ctx.scale(-1, 1);
juego.ctx.drawImage(
img,
tileX * width,
tileY * height,
width,
height,
-x - drawWidth,
y,
drawWidth,
drawHeight
);
juego.ctx.restore();
} else {
juego.ctx.drawImage(
img,
tileX * width,
tileY * height,
width,
height,
x,
y,
drawWidth,
drawHeight
);
2021-06-28 18:01:45 +00:00
}
2021-06-30 23:16:45 +00:00
}
2021-06-28 18:01:45 +00:00
2021-06-30 23:16:45 +00:00
return { getWidth, getHeight, draw, width, height };
2021-06-28 18:01:45 +00:00
}