Ajouter un arrière-plan

pour Santa (Villette Makerz)

Les arrière-plans permettent de donner une tonalité à l'ensemble de ton niveau et de renforcer l'immersion du joueur.

Importer une image

Pour commencer, il va te falloir une image. Réalises-en une si tu ne l'as pas déjà fait, ou utilise celle ci-dessous (click droit -> enregistrer-sous).

Charger l'image dans le programme

Importe ensuite ton image dans ton projet en la plaçant dans le bon dossier : assets/sprites/. Puis, ajoute cette ligne au début de ton script game.js, comme suit.

// chargement des images du jeu
loadSprite( "bean"   , "assets/sprites/bean.png"   ) ;
loadSprite( "grass"  , "assets/sprites/grass.png"  ) ;
loadSprite( "portal" , "assets/sprites/portal.png" ) ;

loadSprite( "background" , "assets/sprites/background.png" ) ;

Déclarer un nouvel objet

Nous allons maintenant déclarer un nouvel objet dans ta scène. Dans le script game.js, trouve la scène game et ajoutes-y le code ci-dessous, comme suit.

// ajoute le niveau
const level = addLevel( LEVELS[ CURRENT_LEVEL ] , LEVEL_CONFIG ) ;

// arrière plan const background = add( [ sprite( "background" , { width : width() , height : height() } ) , layer("background") , pos(0,0), scale(1), fixed(), "background", ] ) ;
// définition du joueur const player = add( [ pos(0,0) , area() , body() , controller() , sprite( "bean" ) , origin( "center" ) , "player" , ] ) ;

BONUS : Animer l'arrière plan

pour Yohan (Deuil-la-Barre)

Créer un nouveau composant

Pour réaliser cet effet, nous allons devoir créer un composant. Rends-toi dans le script component.js et ajoutes-y cette fonction.

// composant permettant d'animer l'arrière plan function movingBackground( scaling = 1.4 , movement = 0.1 ){ const x = width() / 2 - width() / 2 * scaling ; const y = height() / 2 - height() / 2 * scaling ; const ax = width() * movement / 2 ; const ay = height() * movement / 2 ; let w = 0 ; let h = 0 ; return { load() { h = LEVELS[CURRENT_LEVEL].length; for (let i = 0 ; i < h ; i++) { let n = LEVELS[CURRENT_LEVEL][i].length; if (n>w) w=n; } every("background", (e) => { e.scale = scaling ; }); }, update() { const vx = this.pos.x / ( w * LEVEL_CONFIG.width ) - 0.5 * 2 ; const vy = this.pos.y / ( h * LEVEL_CONFIG.height ) - 0.5 * 2 ; every("background", (e) => { e.pos.x = x - vx * ax ; e.pos.y = y - vy * ay ; }); }, } }

Ajouter le nouveau composant

Nous devons maintenant ajouter ce nouveau composant au joueur. Dans le script game.js, à l'intérieur de la scène game, trouve la variable player et ajoutes-y cette ligne.

// définition du joueur
const player = add([

  pos(0,0) ,
  area() ,
  body() ,
  controller() ,
  sprite( "bean" ) ,
  origin( "center" ) ,

  movingBackground(),

  "player" ,

]);