gpt4 book ai didi

javascript - Webgl - 纹理坐标偏移

转载 作者:行者123 更新时间:2023-11-29 18:10:30 24 4
gpt4 key购买 nike

我正在学习 webGL,但遇到了这个我无法解决的问题:

我正在制作一个简单的拼贴游戏进行练习,我为所有纹理使用一个图像。当我为某个顶点指定一个纹理坐标时,它有时会有一点偏移,这可以让你看到其他纹理的一部分。

你可以看到这个 here 的例子(我已经倾斜了结果,以便可以更容易地看到纹理偏移)

纹理图像为 64x64,每个图 block 为 8x8。我计算每个顶点的纹理坐标的方式是这样的:

y0=1-(textp%8)/8;
y1=1-(textp%8+1)/8;
x0=Math.floor(textp/8)/8;
x1=Math.floor(textp/8+1)/8;

提前致谢。

编辑:这是问题的屏幕截图。
le screenshot

最佳答案

我不确定完美的解决方案。

一种方法是始终使用像素坐标。我猜问题是您尝试显示的图 block 不在完美的像素边界上(就像您将 map 向下滚动 1.5 像素一样)?

I solved it by not using texture coordinates for my tiles and doing all my tiling in the fragment shader

我想因为我必须在 SO 上发布代码,所以这里有一些代码

顶点着色器

attribute vec4 position;
attribute vec4 texcoord;

uniform mat4 u_matrix;
uniform mat4 u_texMatrix;

varying vec2 v_texcoord;

void main() {
gl_Position = u_matrix * position;
v_texcoord = (u_texMatrix * texcoord).xy;
}

片段着色器

precision mediump float;

uniform sampler2D u_tilemap;
uniform sampler2D u_tiles;
uniform vec2 u_tilemapSize;
uniform vec2 u_tilesetSize;

varying vec2 v_texcoord;

void main() {
vec2 tilemapCoord = floor(v_texcoord);
vec2 texcoord = fract(v_texcoord);
vec2 tileFoo = fract((tilemapCoord + vec2(0.5, 0.5)) / u_tilemapSize);
vec4 tile = floor(texture2D(u_tilemap, tileFoo) * 256.0);

float flags = tile.w;
float xflip = step(128.0, flags);
flags = flags - xflip * 128.0;
float yflip = step(64.0, flags);
flags = flags - yflip * 64.0;
float xySwap = step(32.0, flags);
if (xflip > 0.0) {
texcoord = vec2(1.0 - texcoord.x, texcoord.y);
}
if (yflip > 0.0) {
texcoord = vec2(texcoord.x, 1.0 - texcoord.y);
}
if (xySwap > 0.0) {
texcoord = texcoord.yx;
}

vec2 tileCoord = (tile.xy + texcoord) / u_tilesetSize;
vec4 color = texture2D(u_tiles, tileCoord);
if (color.a <= 0.1) {
discard;
}
gl_FragColor = color;
}

该技术的详细信息 are here但它的简短版本是查看着色器中的瓦片贴图以确定要显示的瓦片。

That code is here在同一个仓库中是加载 Tiled maps 的代码主要用于 this project .

注意:我遇到了同样的问题trying to do with vertex texture coords .由于在没有他们的情况下这样做对我有用,所以我没有研究为什么它不起作用。所以我想这不是你问题的直接答案。我想我希望这是一个解决方案。

关于javascript - Webgl - 纹理坐标偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27826784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com