From d08e0105cbc59c6cc804f04aaf1e4e625a13960c Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Fri, 1 Mar 2024 19:45:33 -0700 Subject: eyes follow cursor --- src/engine/systems/FacingDirection.ts | 63 +++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/engine/systems/FacingDirection.ts (limited to 'src/engine/systems/FacingDirection.ts') diff --git a/src/engine/systems/FacingDirection.ts b/src/engine/systems/FacingDirection.ts new file mode 100644 index 0000000..f831bf6 --- /dev/null +++ b/src/engine/systems/FacingDirection.ts @@ -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( + ComponentNames.BoundingBox, + )!; + const facingDirection = entity.getComponent( + 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(ComponentNames.Sprite); + const sprite = facingDirection.directionSprites.get(direction)!; + sprite.fillTimingsFromSprite(oldSprite); + + entity.addComponent(sprite); + }, + ); + } +} -- cgit v1.2.3-70-g09d2