-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.ts
More file actions
55 lines (47 loc) · 1.49 KB
/
utils.ts
File metadata and controls
55 lines (47 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Vector } from "../../utils";
import { TILE_SIZE } from "../../constants";
import { Input, WIDTH, HEIGHT, TILE_X, TILE_Y, SPEED } from "./constants";
export const getSpritePos = (direction: Vector, currentFrame: number) => {
let yMultiplier = 0;
if (direction.eq(Vector.Up)) {
yMultiplier = 4;
} else if (direction.eq(Vector.Left)) {
yMultiplier = 6;
} else if (direction.eq(Vector.Right)) {
yMultiplier = 2;
}
return {
tileX: TILE_X + WIDTH * currentFrame,
tileY: TILE_Y + TILE_SIZE * yMultiplier,
};
};
export const drawFrame = (
ctx: CanvasRenderingContext2D,
tileSet: CanvasImageSource,
direction: Vector,
currentFrame: number
) => {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
const { tileX, tileY } = getSpritePos(direction, currentFrame);
ctx.drawImage(tileSet, tileX, tileY, WIDTH, HEIGHT, 0, 0, WIDTH, HEIGHT);
};
export const getInputVector = (key: string) => {
if (Input.Up.includes(key)) {
return Vector.Up;
} else if (Input.Down.includes(key)) {
return Vector.Down;
} else if (Input.Left.includes(key)) {
return Vector.Left;
} else if (Input.Right.includes(key)) {
return Vector.Right;
}
return Vector.Zero;
};
export const move = (direction: Vector, canvas: HTMLCanvasElement) => {
if (direction.eq(Vector.Zero)) {
return;
}
const velocity = direction.mul(SPEED);
canvas.style.top = `${parseInt(canvas.style.top || "0") - velocity.x}px`;
canvas.style.left = `${parseInt(canvas.style.left || "0") + velocity.y}px`;
};