salva-la-costanera/src/utils.ts

48 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-06-30 21:18:13 +00:00
import { Juego } from "./main";
2021-06-28 18:01:45 +00:00
export type Pos = {
x: number, y: number,
};
export type Box = Pos & {
width: number, height: number,
}
2021-06-30 21:18:13 +00:00
2021-06-28 18:01:45 +00:00
export function posInBox(box: Box, pos: Pos) {
return pos.x > box.x && pos.x < box.x + box.width
&& pos.y > box.y && pos.y < box.y + box.height
}
2021-06-28 19:02:12 +00:00
export function boxCollision(box1: Box, box2: Box) {
// http://stackoverflow.com/questions/2440377/ddg#7301852
return !(
((box1.y + box1.height) < (box2.y)) ||
(box1.y > (box2.y + box2.height)) ||
((box1.x + box1.width) < box2.x) ||
(box1.x > (box2.x + box2.width))
)
}
2021-06-28 18:01:45 +00:00
2021-06-30 21:18:13 +00:00
export function drawText(juego: Juego<any>, text: string, pos: Pos, {
bold = false,
size = 2,
align = "left",
baseline = "top",
}: {
align?: CanvasTextAlign,
baseline?: CanvasTextBaseline,
bold?: boolean,
// in rem
size?: number,
}): Box {
juego.ctx.font = `${bold ? 'bold ' : ''}${size}rem sans-serif`
juego.ctx.textAlign = align
juego.ctx.textBaseline = baseline
juego.ctx.fillText(text, pos.x, pos.y)
const measure = juego.ctx.measureText(text)
return { ...pos, width: measure.width, height: measure.actualBoundingBoxDescent }
}
export function randomFromArray<T>(array: T[]): T {
return array[Math.floor(Math.random() * array.length)]
}