简体   繁体   English

向滚动背景添加视差

[英]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. 现在,我要根据播放器的x / y位置在不同位置绘制四个背景实例,因此它们将随播放器一起移动。

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. 随着玩家远离(0,0),他看到的背景越来越少,因为它似乎以更快的速度超越了他。 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. 您可以简单地将CSS用于背景图像,并根据需要调整背景位置。

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. 可以用您要移动的值替换-1的背景X位置。

bgx -= 1;

Then for each loop the background position is updated (Y position is fixed in this example): 然后为每个循环更新背景位置(在此示例中,Y位置是固定的):

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. bgx以某种方式等于图像的最大宽度时,只需将其重置为开始即可。

Use 2 canvases -- one placed directly on top of the other 使用2张画布-一个直接放在另一个上

  • 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. 这样,您可以为每个画布使用不同的动画速度来创建视差效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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