移动“相机” HTML Canvas 元素的

发布于 2024-12-18 17:57:21 字数 189 浏览 1 评论 0原文

我正在尝试找到一种干净的方法来“移动画布元素的相机”。

这是我的原型游戏(横向卷轴)。我很乐意认为有一个比移动整组节点来模拟移动的“相机”更好的解决方案。

我几乎肯定已经阅读了一个简单的操作方法(使用偏移量?),但事实上我没有找到类似的东西,这开始引起怀疑......我是否想象过阅读它!?

谢谢你帮我澄清... J

I'm trying to find a clean way to "move the camera" of a canvas element.

This for my prototype game (side scroller). I'd love to think there's a better solution than moving the whole set of nodes to simulate a "camera" moving around.

Am almost certain to have read a simple how-to (using offsets?) but the fact I don't find anything like that starts to raise doubts... have I imagined reading that!?

Thanks to help me clarify...
J

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征﹌骨岁月お 2024-12-25 17:57:21

假设您每秒重绘整个游戏场景 30 次(或多或少),

您需要重绘整个游戏场景,但首先将 Canvas 上下文平移一定的偏移量。

context.translate(x,y) 正是您想要的。您需要了解其用法以及 save()restore() 方法。

当您翻译上下文时,之后绘制的所有内容都会移动该量。

因此,您不断使用 drawImage(badguy,50,50) 在 50,50 处绘制某些东西(可能是敌人)。然后玩家移动,这会将 translatex 更改为 -1(因为玩家向右移动)而不是 0。您仍然用命令drawImage(badguy,50,50),但是当你绘制它时,由于context.translate(-1,0)<,敌人显示得好像在49,50 /code> 命令移动其之前的所有内容绘制的。

当然,当您进入表演领域时,您会希望确保您只绘制可以在屏幕上实际看到的东西!如果您的 context.translate(-2000,0) 水平太低,您不想再在 50,50 处绘制对象,而只想绘制与可视区域相交的对象。

Presumably you redraw your whole game scene 30 times a second (more or less)

You need to redraw your whole game scene but first translate the Canvas context by some offset.

context.translate(x,y) is precisely what you want. You'll want to read up on the use of that as well as the save() and restore() methods.

When you translate the context, everything drawn afterwards is shifted by that amount.

So you constantly draw something (maybe an enemy) at 50,50 using drawImage(badguy,50,50). Then the player moves, which changes the x of translate to -1 (because the player is moving to the right) instead of 0. You still draw the enemy sprite with the command drawImage(badguy,50,50), but when you draw it the enemy shows up as if it were at 49,50 because of the context.translate(-1,0) command shifting everything before its drawn.

Of course when you get into performance you'll want to be making sure that you are only ever drawing things that can actually be seen on the screen! If your are far down the level with context.translate(-2000,0), you dont want to be drawing objects at 50,50 anymore, only ones that intersect the viewable area.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文