Utiliser une caméra avec un décalage

La camera avec un décalage peut permettre de mettre en avant les éléments qui sont dans la direction du joueur et ainsi l'aider à anticiper ses déplacements. Cette caméra est capable de s'adapter aux changements de direction du joueur, elle est toutefois plus adaptée pour des niveaux plutôt linéaires avec peu de changements de direction.

Créer un nouveau composant

view.js
function offsetCamera(tag = "player") { // permet à la caméra de suivre un objet avec un décalage const offset_x = 120 const offset_y = 40 const margin_x = 100 const margin_y = 100 const anim_delay = 0.4 const screen_ratio = 600 let rec_pos , targets let target_pos=vec2( -1 , -1 ) , current_pos=vec2( -1 , -1 ) return { id : "camera" , pos : null , zoom : null , add() { targets = get(tag, { recursive: true , liveUpdate: true } ) if (targets.length>0) { rec_pos = targets[0].pos targets[0].onPhysicsResolve( () => this.setPos(targets[0]) ) } }, update() { if (targets.length>0) this.setPos(targets[0]) this.zoom = height()/screen_ratio camScale( this.zoom ) }, setPos(trgt) { const dist = rec_pos.sub(trgt.pos) ; if ( dist.x < - margin_x ) target_pos.x = -1 if ( dist.x > margin_x ) target_pos.x = 1 if ( dist.y < - margin_y ) target_pos.y = -1 if ( dist.y > margin_y ) target_pos.y = 1 rec_pos.x = clamp( rec_pos.x , trgt.pos.x - margin_x , trgt.pos.x + margin_x ) rec_pos.y = clamp( rec_pos.y , trgt.pos.y - margin_y , trgt.pos.y + margin_y ) tween( current_pos , target_pos , anim_delay , (p) => current_pos = p , easings.linear ) this.pos = trgt.pos.sub( current_pos.scale( offset_x , offset_y ) ) camPos( this.pos ) }, } }

Modifier la caméa

game.js
scene("game", () => { // scène dans laquelle se déroulent les niveaux setGravity(3200) ; setBackground( [ 141 , 183 , 255 ] ) ; const level = addLevel( LEVELS[ CURRENT_LEVEL ] , levelConf ) const camera = add( [ multiplayerCamera( ) ] ) const camera = add( [ offsetCamera( ) ] ) if (debugmode) debug.inspect = true })

l'objet auquel la caméra est attachée

Le premier paramètre du composant offsetCamera permet de spécifier quel objet la caméra doit suivre. Il est possible de créer son propre identifiant et de l'attribuer à l'objet de son choix.

const camera = add( [ offsetCamera( "player" ) ] )