sight
permet à un objet de repérer d'autres objet
triggers on self
"target found"parameters
| Parameter | Default Value | Type | Description |
|---|---|---|---|
sight | number | 180 | |
looseSight | number | 340 | |
raycast | boolean | false | |
tag | string | 'player' | |
rayCastExclude | array | ['pass through'] | |
offset | vec2 | vec2(0, 0) | |
on | boolean | true | |
offScreenPaused | boolean | false | |
liveUpdate | boolean | false | |
onAddOnly | boolean | false |
example
sight({ sight: 180, looseSight: 340, raycast: false, tag: 'player', rayCastExclude: ['pass through'], offset: vec2(0, 0), on: true, offScreenPaused: false, liveUpdate: false, onAddOnly: false}),function sight(p) { const param = { sight: 180, looseSight: 340, raycast: false, tag: 'player', rayCastExclude: ['pass through'], offset: vec2(0, 0), on: true, offScreenPaused: false, liveUpdate: false, onAddOnly: false, ...p, }; return { id: 'sight', sightOn: param.on, currentTarget: null, add() { const isAlive = (obj) => { return !obj.has('alive') || obj.isAlive == true; }; const isPaused = () => { return param.offScreenPaused && this.isOffScreen(); }; const raycastCheck = (target) => { if (!param.raycast) return true; this.area.scale = vec2(0, 0); const level = this.getLevel(); if (level) { const r = this.getLevel().raycast( this.pos.add(param.offset), target.pos.sub(this.pos), param.rayCastExclude ); if (debug.inspect) drawLine({ p1: this.pos.add(param.offset), p2: target.pos, width: 4, color: rgb(0, 0, 255), }); this.area.scale = vec2(1, 1); return r != undefined && r.object && r.object.id == target.id; } return false; }; const isTargetStillOnSight = (target) => { return ( target.pos.dist(this.pos) <= param.looseSight && raycastCheck(target) ); }; const getClosestTarget = (target) => { const targets = get(param.tag, { recursive: true }); let closestTarget, lastDistance; for (const target of targets) { const distance = this.pos.add(param.offset).dist(target.pos); if ( target != this && isAlive(target) && distance <= param.sight && (lastDistance == null || lastDistance > distance) && (!target.collisionIgnore || !target.collisionIgnore.includes('*')) && raycastCheck(target) ) { lastDistance = distance; closestTarget = target; } } this.currentTarget = closestTarget; if (closestTarget) this.trigger('target found'); }; if (param.onAddOnly) requestAnimationFrame(() => getClosestTarget()); else onUpdate(() => { if (this.currentTarget && !isTargetStillOnSight(this.currentTarget)) this.currentTarget = false; if ( param.liveUpdate || (!this.currentTarget && !isPaused() && isAlive(this) && this.sightOn) ) getClosestTarget(); }); }, };}