Personnages qui suivent les joueurs

Charger une image

load.js
const PNG = [ "kat", "grass", ]

Créer un composant

component.js
// Ajoutes ici tes propres composants
function followTarget(p) { // permet à un objet de suivre un autre objet 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", update() { if (this.retreatPos == null) this.retreatPos = vec2(this.pos) if (!this.isTargetOnSight()) this.target = this.getClosestTarget() this.runBy() }, runBy() { const gravity = this.gravityScale != 0 let t 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.x > 0) this.facing = 1 else if (this.direction.x < 0) this.facing = -1 }, 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 } } return closestTarget }, isTargetOnSight() { return ( this.target != null && this.target.pos.dist(this.pos) < param.loosingSight ) }, } }

Déclarer un symbole

levelConf.js
const LEVEL_CONFIG = { // paramètres du niveau tileWidth: 64, tileHeight: 64, backgroundColor: "afe1ff", gravity: 3200, tiles: { // listes des objets à placer dans les niveaux
"k": () => [ // chat passif sprite("kat"), area(), anchor("bot"), body(), followTarget({ stopDistance: 120 }), falling(), scale(), respawn({ live: true }), opacity(), ], "K": () => [ // chat hostile sprite("kat"), area(), anchor("bot"), body(), followTarget({ jumping: false }), coloring({ color: Color.fromHex("ff9696") }), danger({ tag: "player" }), scale(), falling(), respawn(), opacity(), alive(), health(1), ],
"#": () => [ // player sprite("bean"), platformerController(), alive(), opacity(), scale(), health(1, 4), area(), anchor("bot"), body(), respawn(), falling(), coloring(), animator(), ], "=": () => [ // bloc sprite("grass"), area(), body({ isStatic: true }), anchor("bot"), offscreen({ hide: true }), ], }, }

Placer les objets

level.js
const LEVELS = [ // liste des niveaux du jeu { map: ` === # K k =========== `, }, ];