I'm trying to write a shader that only maps a portion of a large texture to my sprite and I'm getting a strange behaviour with my current code.
This is what I have right now:
Texture atlas example (256x256px):
EDIT
I've changed both shaders and I get the following output right now (first image), but I need to zoom the texture so I only render the highlighted portion of the second image, how should I modify the shaders to achieve that?
->
These are my current shaders:
Vertex:
uniform mat4 uMVPMatrix;
attribute vec4 aPosition;
attribute vec2 aTextureCoord;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
// offset and texSize will be defined as attributes later.
// They're defined here for test purposes only
vec2 offset = vec2(128.0, 64.0);
vec2 texSize = vec2(256.0, 256.0);
float u = offset.x / texSize.x;
float v = offset.y / texSize.y;
vTextureCoordOffset = vec2(u, v);
vTextureCoord = aTextureCoord;
gl_Position = uMVPMatrix * aPosition;
}
Fragment:
precision mediump float;
uniform sampler2D sTexture;
varying vec2 vTextureCoord;
varying vec2 vTextureCoordOffset;
void main() {
gl_FragColor = texture2D(sTexture, fract(vTextureCoord) + vTextureCoordOffset);
}
SOLVED
I solved it changing the fragment shader to:
gl_FragColor = texture2D(sTexture, fract(vTextureCoord) * vZoom + vTextureCoordOffset);
vZoom is calculated in the vertex shader:
vZoom = subTextureSize / texSize;