简体   繁体   中英

Adding parallax to scrolling background

I'm making a canvas game where you travel in a spaceship over an endless repreating background. Right now I'm drawing four instances of the background at different positions based off of the player's x/y position, so they will move with the player.

ctx.translate(ax,ay);
ctx.drawImage(Ibg,Math.round(x/1080)*1080,Math.round(y/720)*720,1080,720);
ctx.drawImage(Ibg,(Math.round(x/1080)*1080)-1080,Math.round(y/720)*720,1080,720);
ctx.drawImage(Ibg,Math.round(x/1080)*1080,(Math.round(y/720)*720)-720,1080,720);
ctx.drawImage(Ibg,(Math.round(x/1080)*1080)-1080,(Math.round(y/720)*720)-720,1080,720);

Translating to ax and ay basically allows objects to scroll with the cameras the player moves, since ax and ay are relative to the player's position. I can create a parallax effect by doing this instead:

ctx.translate(ax*.5,ay*.5);

This makes the background scroll slower than other game objects, like I'd like it to. But I still haven't figured out how to adjust the rest of the code to compensate. As the player moves farther from (0,0) he sees less and less of the background, because it seems to go beyond him at a faster rate. How can I fix this?

As an option to markE's answer you don't need to use a second canvas at all (which is a good option to this).

You can simply use CSS for background image and adjust background position with the amount you need.

Demo here

The essential part is simply these lines:

Background X position where -1 can be replaced with the value you want to move it at.

bgx -= 1;

Then for each loop the background position is updated (Y position is fixed in this example):

canvas.style.backgroundPosition = bgx + 'px -30px'; // set X and Y position

When bgx somehow equals the max width of the image you just reset it to the beginning.

Use 2 canvases -- one placed directly on top of the other

  • A "background" canvas is on the bottom and animates more slowly.
  • A "game objects" canvas is on the top and animates more quickly.

That way you can create a parallax effect using different animation speeds for each canvas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM