Charger une image
load.js
const PNG = [
"kat" ,
"grass" ,
"bean" ,
]
Créer un composant
component.js
// Ajoutes ici tes propres composants
function followTarget( speed = 280 , stop_distance = 120 , retreat = false , tag = "player" ) {
const switch_delay = 0.2
const stop_delay = 0.2
const sight = 200
const loosing_sight = 400
const jump_force = 800
const jump = true
return {
direction : vec2( 0 , 0 ) ,
facing : 1 ,
target : null ,
retreatPos : null ,
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>stop_distance) t = this.target.pos.sub( this.pos )
else t = vec2(0,0) ;
if( gravity && jump && t.y<-1 && this.isGrounded()) this.jump(jump_force)
}
else if (retreat) {
const d = this.pos.dist(this.retreatPos)
if (d>stop_distance) 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() , switch_delay,
(p) => this.direction = p ,
easings.easeOutSin
)
this.move(this.direction.scale(speed))
if ( this.direction.x > 0 ) this.facing = 1
else if ( this.direction.x < 0 ) this.facing = -1
},
getClosestTarget(){
const targets = get(tag, { recursive: true } )
let closestTarget , lastDistance
for (const e of targets){
const d = this.pos.dist(e.pos)
if ( ( lastDistance == null || lastDistance > d ) && d < sight ) {
lastDistance = d
closestTarget = e
}
}
return closestTarget
},
isTargetOnSight(){
return this.target!=null && this.target.pos.dist(this.pos) < loosing_sight
},
} }
Déclarer un symbole
level.js
const levelConf = {
// paramètres du niveau
tileWidth: 64,
tileHeight: 64,
tiles: {
// listes des objet à placer dans les niveaux
"K": () => [ // chat
sprite("kat"),
area(),
anchor("bot"),
body(),
followTarget(),
],
"#": () => [ // player
sprite("bean"),
platformerController(),
health(1),
character(),
area(),
anchor("bot"),
body(),
],
"=": () => [ // bloc
sprite("grass"),
area(),
body({ isStatic: true }),
anchor("bot"),
offscreen({ hide: true }),
],
},
}
Placer les objets
level.js
const LEVELS = [
// liste des niveaux du jeu
[
"==== " ,
"= =" ,
"= # =" ,
"= ======" ,
"= K = " ,
"====== " ,
],
];
la vittesse de déplacement
followTarget( 280 )
la distance à laquelle le personnage s'arrête
followTarget( 280 , 120 )
si le personnage retourne à sa position
followTarget( 280 , 120 , true )
le type d'objet que le personnage suit
followTarget( 280 , 120 , true , "player" )