2015-01-07 159 views
2

我學習WebGL和我已經遇到這個問題,我解決不了:WEBGL - 紋理座標偏移

我做一個簡單的瓷磚遊戲,練習和我使用一個圖像的所有紋理。當我爲某個頂點分配一個紋理座標時,它有時會有一點偏移,這使您可以看到其他紋理的一部分。

你可以看到這個here的例子(我傾斜的結果,使紋理偏移可以更容易地看出)

的紋理圖像爲64×64,每瓦是8×8。我計算每個頂點的紋理座標的方式是這樣的:

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

+0

你可以添加截圖嗎?我不確定自己看到了什麼。我看到一個美麗的遊戲。 – Qwerty

+1

我已經添加了截圖的鏈接(我沒有足夠的信譽發佈圖片...)。你可以在河裏看到最好的問題。 (和謝謝) – frwest

+0

那麼,我沒有看到任何這在Firefox或鉻..是你的瀏覽器放大? – Qwerty

回答

4

我不確定完美的解決方案。

人們總是會使用像素座標。我猜測問題是你試圖顯示的圖塊不在完美的像素邊界上(就像你將地圖向下滾動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。由於沒有他們這樣做,我沒有看到爲什麼它不工作。所以我想這不是對你的問題的直接回答。我想我希望這是一個解決方案。