'How do I use OpenGL to make spritesheet animation?
I have a spritesheet consisting of 8 sprites, each of which is a frame in an animation. I have written shaders to display the first frame of the animation with OpenGL, but I do not know how to switch to the second frame.
Solution 1:[1]
You can switch the sprites with a fragment shader by texture sampling. Say your spritesheet consists of 8 * 6 sprites (2D spritesheet), each sprite can be extracted as follows.
#version 400 core
in vec2 v_uvs;
uniform sampler2D u_texture;
uniform float u_time; // sec
out vec4 fragColor;
const float SPRITE_COLUMNS = 8.0;
const float SPRITE_ROWS = 6.0;
const uint NUM_OF_SPRITES = 48;
void main(void) {
uint sprite_idx = int(u_time * 20) % NUM_OF_SPRITES;
vec2 pos = vec2(sprite_idx % int(SPRITE_COLUMNS), int(sprite_idx / SPRITE_COLUMNS));
fragColor = texture(u_texture, vec2((v_uvs.x / SPRITE_COLUMNS) + pos.x * (1.0 / SPRITE_COLUMNS),
(v_uvs.y / SPRITE_ROWS) + pos.y * (1.0 / SPRITE_ROWS)));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler2P |
