45 Fake3D background - JcerelusDev/CanvasGameJs GitHub Wiki

What is the Fake3D or parallax background?

Fake3D background is a method that allows us to add a fake 3d depth in our 2d game, by adding different background layers and each with different speed depending on our needs.

How to use it ?

It is simple to use :

You should have images with the same width else it won't work. Width of images is not the width you give in javascript, but the main width of the images.

var bg1 = new Image()
bg1.src ="bg1.png"
var bg2 = new Image()
bg2.src ="bg2.png"
var bg3 = new Image()
bg3.src ="bg3.png"

var layer1 = new layerB(bg1,0,0,1200,500,0.8)

var layer2 = new layerB(bg1,0,0,1200,300,0.3)

var layer3 = new layerB(bg1,0,0,1200,100,1)

To draw multiple layers we need to save them in an array like below

var BgLayers [layer1,layer2,layer3]

function drawParallax(){
for(BLayer of BgLayers){
BLayer.update()
BLayer.draw()
}

}

Remember you need to draw the parallax before the camera system.

In the render function do the following :

game.render = function(){
drawParallax()
game.setCam(player)
}

Good to know

<< gameFrame is a bult in variable.>>

for the parallax to work you need to use tha gameFrame variable in your left controller and right controller movement.

function moveLeft(){
player.vx = - 8
player.x +=player.vx
gameFrame++
}

function moveRight(){
player.vx = 8
player.x +=player.vx
gameFrame--
}


```