在 JavaScript 画布中复制图块区域
我有一个显示瓦片地图的画布。滚动时,我不想刷新整个图块列表,而是想选择可以重复使用的图块地图的有用部分并将其复制到另一个画布。
例如,如果图块地图跨度为 5 个图块:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
并且我想向右移动 (x) 1 个图块...我可以复制图块 1 到 4,因为这些图块将在下一帧中使用。所以我会复制:
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
我似乎在为此提出正确的数学方面遇到问题。
目前我有以下代码:
// Calculate from and to for x and y
// Change formula if positive or negative movement
// movX / movY = amount to move across x or y
// (i.e. movX = 1 (right) or movX = -1 (left)
// tileXFrom / tileYFrom = tile to start copy from
// tileXTo / tileYTo = tile to finish copying at
if(movX > 0)
{
tileXFrom = origX + movX;
tileXTo = tileXFrom + (tilesCountX - movX);
}
else
{
tileXFrom = origX;
tileXTo = tileXFrom + (tilesCountX + movX);
}
if(movY > 0)
{
tileYFrom = origY + movY;
tileYTo = tileYFrom + (tilesCountY - movY);
}
else
{
tileYFrom = origY;
tileYTo = tileYFrom + (tilesCountY + movY);
}
这些计算工作正常,但是有更好的方法吗?我想知道是否有办法绕过正/负 if 语句。
我现在陷入困境的部分是如何获得每个的真实 x, y 位置。
因此,我需要将图块 1, 0 转换为屏幕上的 x, y 位置,以便从那里开始复制。
如果这一切都有意义的话?
干杯
I have a canvas displaying a tile map. When scrolling, rather than refreshing the entire tile list, I want to select the useful part of the tile map that I can reuse and copy it to another canvas.
For example, if the tile map was 5 tiles across:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
And I wanted to move right (x) 1 tile... I could copy tiles 1 to 4 as these will be used in the next frame. So I would copy:
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
I seem to be having a problem coming up with the right maths for this.
At the moment I have the following code:
// Calculate from and to for x and y
// Change formula if positive or negative movement
// movX / movY = amount to move across x or y
// (i.e. movX = 1 (right) or movX = -1 (left)
// tileXFrom / tileYFrom = tile to start copy from
// tileXTo / tileYTo = tile to finish copying at
if(movX > 0)
{
tileXFrom = origX + movX;
tileXTo = tileXFrom + (tilesCountX - movX);
}
else
{
tileXFrom = origX;
tileXTo = tileXFrom + (tilesCountX + movX);
}
if(movY > 0)
{
tileYFrom = origY + movY;
tileYTo = tileYFrom + (tilesCountY - movY);
}
else
{
tileYFrom = origY;
tileYTo = tileYFrom + (tilesCountY + movY);
}
These calculations work fine however is there a better way to do them? I'm wondering if there is a way round the positive / negative if statement.
The part where I am now stuck at is what to do to get the real x, y positions for each.
So I need to convert tile 1, 0 to an on screen x, y position in order to start the copy from there.
If that all makes sense?!
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用三元运算符来缩短代码,但这不会改变功能:
You can use ternary operators to shorten the code, but this won't change the functionality: