followTarget
Permet à un objet de suivre un autre objet
triggers on self
"spotted"parameters
| Parameter | Default Value | Type | Description |
|---|---|---|---|
speed | number | 280 | |
stopDistance | number | 0 | |
retreat | boolean | false | |
tag | string | "player" | |
uTurnDelay | number | 0.2 | |
sight | number | 200 | |
loosingSight | number | 400 | |
jumpForce | number | 800 | |
jumping | boolean | true |
example
followTarget({ speed: 280, stopDistance: 0, retreat: false, tag: "player", uTurnDelay: 0.2, sight: 200, loosingSight: 400, jumpForce: 800, jumping: true}),function followTarget(p) { const param = { speed: 280, stopDistance: 0, retreat: false, tag: "player", uTurnDelay: 0.2, sight: 200, loosingSight: 400, jumpForce: 800, jumping: true, ...p } return { direction: vec2(0, 0), facing: 1, target: null, retreatPos: null, id: "follow", add() { requestAnimationFrame(() => this.retreatPos = vec2(this.pos)) this.on("respawn", () => this.target = null) }, update() { const isOnSight = this.target != null && this.target.pos.dist(this.pos) < param.loosingSight const gravity = this.gravityScale != 0 let t if (!isOnSight) this.target = this.getClosestTarget() if (this.target) { const d = this.pos.dist(this.target.pos) if (d > param.stopDistance) t = this.target.pos.sub(this.pos) else t = vec2(0, 0) if (gravity && param.jumping && t.y < -1 && this.isGrounded()) this.jump(param.jumpForce) } else if (param.retreat) { const d = this.pos.dist(this.retreatPos) if (d > param.stopDistance) t = this.retreatPos.sub(this.pos) else t = vec2(0, 0) } else t = vec2(0, 0) if (gravity) t.y = 0 tween(this.direction, t.unit(), param.uTurnDelay, (v) => (this.direction = v), easings.easeOutSin) this.move(this.direction.scale(param.speed)) if (this.direction.len() > 0.1) this.facing = this.direction.unit().x }, getClosestTarget() { const targets = get(param.tag, { recursive: true }) let closestTarget, lastDistance for (const e of targets) { const d = this.pos.dist(e.pos) if ((lastDistance == null || lastDistance > d) && d < param.sight) { lastDistance = d closestTarget = e this.trigger("spotted") } } return closestTarget }, }}