import {AutoTargetingScene} from "@avalon/Excalibur/Scene/AutoTargetingScene"; import {Engine} from "excalibur"; const canvasElement = document.createElement('canvas'); document.body.appendChild(canvasElement); const engine = new Engine({ canvasElement, scenes: { example: new AutoTargetingScene(), } }); engine .start('example') .then(() => console.log('✅ Engine started!'));
1import {BaseComponent} from @avalon/Excalibur/Component/BaseComponent;2import {HasTargetComponent} from @avalon/Excalibur/Component/HasTargetComponent;3import {Actor, PreUpdateEvent, TagQuery} from "excalibur";45export class SearchesTargetComponent extends BaseComponent {6 private readonly queryTags: string[];7 private readonly maxDistance?: number;8 private query!: TagQuery<string>;9 private nextCheck: number = 0;1011 constructor({queryTags, maxDistance}: { queryTags: string[], maxDistance?: number }) {12 super();1314 this.queryTags = queryTags;15 this.maxDistance = maxDistance;16 this.on('preupdate', this.onPreUpdate.bind(this));17 }1819 onPreUpdate({engine, delta}: PreUpdateEvent): void {20 const owner = this.owner;21 if (!owner) {22 return;23 }2425 this.nextCheck -= delta;26 if (owner.has(HasTargetComponent) && this.nextCheck > 0) {27 return;28 }2930 if (!this.query) {31 this.query = engine.currentScene.world.queryTags(this.queryTags);32 }3334 let minDistance: number = Infinity;35 let closestTarget: Actor | undefined;3637 for (const target of this.query?.entities ?? []) {38 if (!(target instanceof Actor)) {39 continue;40 }4142 const distance = owner.pos.distance(target.pos);43 if (this.maxDistance && distance > this.maxDistance) {44 continue;45 }4647 if (distance >= minDistance) {48 continue;49 }5051 minDistance = distance;52 closestTarget = target;53 }5455 this.nextCheck = 1000;5657 if (!closestTarget || owner.get(HasTargetComponent)?.target === closestTarget) {58 return;59 }6061 owner.addComponent(new HasTargetComponent(closestTarget), true);62 }63}