eyes follow cursor

This commit is contained in:
Elizabeth Hunt 2024-03-01 19:45:33 -07:00
parent a8d07a7903
commit d08e0105cb
Signed by: simponic
GPG Key ID: 52B3774857EB24B1
13 changed files with 252 additions and 6 deletions

View File

@ -1,7 +1,7 @@
import { Game } from "."; import { Game } from ".";
import { loadAssets } from "./config"; import { loadAssets } from "./config";
import { Player } from "./entities"; import { Player } from "./entities";
import { Render } from "./systems"; import { FacingDirection, Input, Render } from "./systems";
export class TheAbstractionEngine { export class TheAbstractionEngine {
private game: Game; private game: Game;
@ -17,7 +17,14 @@ export class TheAbstractionEngine {
public async init() { public async init() {
await loadAssets(); await loadAssets();
[new Render(this.ctx)].forEach((system) => this.game.addSystem(system)); const inputSystem = new Input();
this.addWindowEventListenersToInputSystem(inputSystem);
const facingDirectionSystem = new FacingDirection(inputSystem);
[new Render(this.ctx), inputSystem, facingDirectionSystem].forEach(
(system) => this.game.addSystem(system),
);
const player = new Player(); const player = new Player();
this.game.addEntity(player); this.game.addEntity(player);
@ -39,4 +46,31 @@ export class TheAbstractionEngine {
this.animationFrameId = null; this.animationFrameId = null;
} }
} }
private addWindowEventListenersToInputSystem(input: Input) {
window.addEventListener("keydown", (e) => {
if (!e.repeat) {
input.keyPressed(e.key.toLowerCase());
}
});
window.addEventListener("keyup", (e) =>
input.keyReleased(e.key.toLowerCase()),
);
window.addEventListener("blur", () => input.clearKeys());
window.addEventListener("mousemove", (e) => {
const canvas = this.ctx.canvas;
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
input.setMousePosition({ x, y });
});
}
} }

View File

@ -3,4 +3,5 @@ export namespace ComponentNames {
export const FacingDirection = "FacingDirection"; export const FacingDirection = "FacingDirection";
export const GridPosition = "GridPosition"; export const GridPosition = "GridPosition";
export const BoundingBox = "BoundingBox"; export const BoundingBox = "BoundingBox";
export const Control = "Control";
} }

View File

@ -0,0 +1,11 @@
import { Component, ComponentNames } from ".";
export class Control extends Component {
public isControllable: boolean = true;
constructor(isControllable = true) {
super(ComponentNames.Control);
this.isControllable = isControllable;
}
}

View File

@ -1,12 +1,18 @@
import { Component, ComponentNames, Sprite } from "."; import { Component, ComponentNames, Sprite } from ".";
import { type Direction } from "../interfaces"; import { Direction } from "../interfaces";
export class FacingDirection extends Component { export class FacingDirection extends Component {
public readonly directionSprites: Map<Direction, Sprite>; public readonly directionSprites: Map<Direction, Sprite>;
public currentDirection: Direction;
constructor() { constructor(currentDirection: Direction = Direction.NONE) {
super(ComponentNames.FacingDirection); super(ComponentNames.FacingDirection);
this.currentDirection = currentDirection;
this.directionSprites = new Map<Direction, Sprite>(); this.directionSprites = new Map<Direction, Sprite>();
} }
public setDirection(direction: Direction) {
this.currentDirection = direction;
}
} }

View File

@ -1,5 +1,6 @@
import { Component, ComponentNames } from "."; import { Component, ComponentNames } from ".";
import type { Dimension2D, DrawArgs, Coord2D } from "../interfaces"; import type { Dimension2D, DrawArgs, Coord2D } from "../interfaces";
import { clamp } from "../utils";
export class Sprite extends Component { export class Sprite extends Component {
private sheet: HTMLImageElement; private sheet: HTMLImageElement;
@ -31,6 +32,11 @@ export class Sprite extends Component {
this.currentFrame = 0; this.currentFrame = 0;
} }
public fillTimingsFromSprite(sprite: Sprite) {
this.msSinceLastFrame = clamp(sprite.msSinceLastFrame, 0, this.msPerFrame);
this.currentFrame = clamp(sprite.currentFrame, 0, this.numFrames - 1);
}
public update(dt: number) { public update(dt: number) {
this.msSinceLastFrame += dt; this.msSinceLastFrame += dt;
if (this.msSinceLastFrame >= this.msPerFrame) { if (this.msSinceLastFrame >= this.msPerFrame) {

View File

@ -4,3 +4,4 @@ export * from "./Sprite";
export * from "./FacingDirection"; export * from "./FacingDirection";
export * from "./GridPosition"; export * from "./GridPosition";
export * from "./BoundingBox"; export * from "./BoundingBox";
export * from "./Control";

View File

@ -1,3 +1,46 @@
export enum Action {
MOVE_LEFT,
MOVE_RIGHT,
MOVE_UP,
MOVE_DOWN,
RESET,
INTERACT,
}
export namespace KeyConstants {
export const KeyActions: Record<string, Action> = {
a: Action.MOVE_LEFT,
arrowleft: Action.MOVE_LEFT,
d: Action.MOVE_RIGHT,
arrowright: Action.MOVE_RIGHT,
w: Action.MOVE_UP,
arrowup: Action.MOVE_UP,
s: Action.MOVE_DOWN,
arrowdown: Action.MOVE_DOWN,
" ": Action.INTERACT,
enter: Action.INTERACT,
};
// value -> [key] from KeyActions
export const ActionKeys: Map<Action, string[]> = Object.keys(
KeyActions,
).reduce((acc: Map<Action, string[]>, key) => {
const action = KeyActions[key.toLowerCase()];
if (acc.has(action)) {
acc.get(action)!.push(key);
return acc;
}
acc.set(action, [key]);
return acc;
}, new Map());
}
export namespace Miscellaneous { export namespace Miscellaneous {
export const WIDTH = 800; export const WIDTH = 800;
export const HEIGHT = 800; export const HEIGHT = 800;

View File

@ -5,6 +5,7 @@ import {
Sprite, Sprite,
GridPosition, GridPosition,
BoundingBox, BoundingBox,
Control,
} from "../components"; } from "../components";
import { Direction } from "../interfaces/"; import { Direction } from "../interfaces/";
@ -19,14 +20,16 @@ export class Player extends Entity {
this.addComponent( this.addComponent(
new BoundingBox( new BoundingBox(
{ {
x: 0, x: 200,
y: 0, y: 200,
}, },
{ width: Player.spriteSpec.width, height: Player.spriteSpec.height }, { width: Player.spriteSpec.width, height: Player.spriteSpec.height },
0, 0,
), ),
); );
this.addComponent(new Control());
this.addComponent(new GridPosition(0, 0)); this.addComponent(new GridPosition(0, 0));
this.addFacingDirectionComponents(); this.addFacingDirectionComponents();
} }

View File

@ -5,3 +5,15 @@ export enum Direction {
RIGHT = "RIGHT", RIGHT = "RIGHT",
NONE = "NONE", NONE = "NONE",
} }
export const angleToDirection = (angle: number): Direction => {
if (angle >= -Math.PI / 4 && angle < Math.PI / 4) {
return Direction.RIGHT;
} else if (angle >= Math.PI / 4 && angle < (3 * Math.PI) / 4) {
return Direction.DOWN;
} else if (angle >= (3 * Math.PI) / 4 || angle < -(3 * Math.PI) / 4) {
return Direction.LEFT;
} else {
return Direction.UP;
}
};

View File

@ -0,0 +1,63 @@
import {
ComponentNames,
FacingDirection as FacingDirectionComponent,
BoundingBox,
Sprite,
} from "../components";
import { Game } from "../Game";
import { System, SystemNames, Input } from ".";
import { Direction, angleToDirection } from "../interfaces";
export class FacingDirection extends System {
private input: Input;
constructor(input: Input) {
super(SystemNames.FacingDirection);
this.input = input;
}
public update(_dt: number, game: Game) {
const mousePosition = this.input.getMousePosition();
const mouseBoundingBox = new BoundingBox(mousePosition, {
width: 0,
height: 0,
});
game.forEachEntityWithComponent(
ComponentNames.FacingDirection,
(entity) => {
if (!entity.hasComponent(ComponentNames.BoundingBox)) {
return;
}
const boundingBox = entity.getComponent<BoundingBox>(
ComponentNames.BoundingBox,
)!;
const facingDirection = entity.getComponent<FacingDirectionComponent>(
ComponentNames.FacingDirection,
);
const { center } = boundingBox;
const angle = Math.atan2(
mousePosition.y - center.y,
mousePosition.x - center.x,
);
const mouseInBoundingBox =
boundingBox.isCollidingWith(mouseBoundingBox);
const direction = mouseInBoundingBox
? Direction.NONE
: angleToDirection(angle);
facingDirection.setDirection(direction);
const oldSprite = entity.getComponent<Sprite>(ComponentNames.Sprite);
const sprite = facingDirection.directionSprites.get(direction)!;
sprite.fillTimingsFromSprite(oldSprite);
entity.addComponent(sprite);
},
);
}
}

View File

@ -0,0 +1,63 @@
import { SystemNames, System } from ".";
import { Game } from "..";
import { ComponentNames } from "../components";
import { Control } from "../components/Control";
import { Action, KeyConstants } from "../config";
import { Entity } from "../entities";
import { Coord2D } from "../interfaces";
export class Input extends System {
private keys: Set<string>;
private mousePosition: Coord2D;
constructor() {
super(SystemNames.Input);
this.keys = new Set();
this.mousePosition = { x: 0, y: 0 };
}
public clearKeys() {
this.keys.clear();
}
public keyPressed(key: string) {
this.keys.add(key);
}
public keyReleased(key: string) {
this.keys.delete(key);
}
public update(_dt: number, game: Game) {
game.forEachEntityWithComponent(ComponentNames.Control, (entity) =>
this.handleInput(entity),
);
}
public handleInput(entity: Entity) {
const controlComponent = entity.getComponent<Control>(
ComponentNames.Control,
);
if (!controlComponent.isControllable) return;
if (this.hasSomeKey(KeyConstants.ActionKeys.get(Action.INTERACT))) {
console.log("interact");
}
}
private hasSomeKey(keys?: string[]): boolean {
if (keys) {
return keys.some((key) => this.keys.has(key));
}
return false;
}
public setMousePosition(mousePosition: Coord2D) {
this.mousePosition = mousePosition;
}
public getMousePosition(): Coord2D {
return this.mousePosition;
}
}

View File

@ -4,4 +4,5 @@ export namespace SystemNames {
export const Input = "Input"; export const Input = "Input";
export const Collision = "Collision"; export const Collision = "Collision";
export const WallBounds = "WallBounds"; export const WallBounds = "WallBounds";
export const FacingDirection = "FacingDirection";
} }

View File

@ -1,3 +1,5 @@
export * from "./SystemNames"; export * from "./SystemNames";
export * from "./System"; export * from "./System";
export * from "./Render"; export * from "./Render";
export * from "./Input";
export * from "./FacingDirection";