BLOG

Notes from the KAYAC hyper-casual team

[WebGL] Sprite Animation in 3D Space Using Shaders

Takumi Fukasawa

Introduction

As the title says, this post shows how to implement sprite animation in WebGL.

Recently, on a WebGL project at work, I ended up using a lot of sprite animations as effects in 3D space and looked into various ways of doing it, so I'd like to walk through it step by step.

Here's the finished result!

The finished loop sprite animation

threejs: loop sprite animation

The sprite image, frames numbered 1 to 16

↑↑ This is the sprite image. The frames are numbered 1 to 16.

How to do sprite animation in WebGL

There are probably other ways too, but these are the ones that come to mind right away.

  1. Load as many frame images (one per frame of the sprite image) as you want to use, make a plane polygon for each image, and switch the planes between shown and hidden as time passes
  2. Pass several frame-image textures to one plane polygon, and switch the texture itself as time passes
  3. Use the sprite image as a texture and animate it by shifting the texture coordinates (UV coordinates from here on) as time passes

Option 1 has drawbacks: depending on the implementation, it adds unnecessary draw calls, and the more frame images you want to animate, the more image requests and textures you need, which can contribute to memory pressure.

Option 2 has the same drawback: the number of requests and textures goes up.

When building a site, you want to keep the number of requests and the rendering load down, so these are drawbacks you'd rather avoid.

1. Show a frame by shifting the UV coordinates

With option 3, using a sprite image and shifting the UV coordinates as time passes, you keep the number of images down and the draw calls don't increase much, so this approach keeps the load on the browser low.

This sample uses three.js, a popular WebGL library, but it has no built-in sprite-sheet animation, so you need to write your own shader.

To take it one step at a time, let's start by showing just "6" without any animation.

1-1. Scale the UV coordinates

Scaling the UV coordinates to the size of one frame

First, scale the UV coordinates to fit the size of each frame. In the sample image there are 4 frames across and 4 down, so we prepare a scaling matrix that shrinks the coordinates to 1/4 both horizontally and vertically.

In WebGL the origin of the UV coordinates is at the bottom left, so they shrink as shown in the figure above.

mat3 scaleMat = mat3(
  1.0 / 4.0, 0.0, 0.0, // shrink horizontally by the number of cells in a row (shrink by 4 frames)
  0.0, 1.0 / 4.0, 0.0, // shrink vertically by the number of cells in a column (shrink by 4 frames)
  0.0, 0.0, 1.0
);

1-2. Translate the UV coordinates

Translating the scaled UV coordinates to the cell for "6"

Next, we make a matrix that translates the UV coordinates to the position of the target cell. The "6" frame is the second from the left in its row and the third from the bottom in its column, so the scaled UV coordinates are moved to the position shown in the figure above.

Note that the column is counted from the bottom. As mentioned above, this is because the origin of the UV coordinates is at the bottom left.

mat3 translateMat = mat3(
  1.0, 0.0, 1.0, // translate horizontally (to the 2nd frame from the left in the row)
  0.0, 1.0, 2.0, // translate vertically (to the 3rd frame from the bottom in the column)
  0.0, 0.0, 1.0
);    

1-3. Apply the coordinate transform

Multiply the two matrices we just made, the scaling matrix and the translation matrix, to get a transform matrix for shifting the UV coordinates. Matrix calculations in WebGL are column-major, so you need to be careful about the order of multiplication.

Here is the full vertex shader. In this example, I pass the transform matrix and the original UV coordinates to the fragment shader.

varying vec2 v_uv;
varying mat3 v_spriteMat;
  
void main(void) {
  mat3 scaleMat = mat3(
    1.0 / 4.0, 0.0, 0.0, // shrink horizontally by the number of frames in a row (shrink by 4 frames)
    0.0, 1.0 / 4.0, 0.0, // shrink vertically by the number of frames in a column (shrink by 4 frames)
    0.0, 0.0, 1.0
  );
    
  mat3 translateMat = mat3(
    1.0, 0.0, 1.0, // translate horizontally (to the 2nd frame from the left in the row)
    0.0, 1.0, 2.0, // translate vertically (to the 3rd frame from the bottom in the column)
    0.0, 0.0, 1.0
  );    
    
  v_spriteMat = translateMat * scaleMat; // make the transform matrix for shifting the UV coordinates
  v_uv = uv;
  
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
}

1-4. Get the image color from the transformed UV coordinates

Here is the full fragment shader. It multiplies the UV coordinates passed from the vertex shader by the transform matrix to get the UV coordinates of each cell, then fetches the color with texture2D. It's simple compared with the vertex shader.

And with that, the "6" frame shows up!!!!!

The link to the sample that shows "6" is below.

uniform sampler2D u_texture;
  
varying vec2 v_uv;
varying mat3 v_spriteMat;

void main(void) {
  vec3 uv = vec3(v_uv, 1.0);
  uv *= v_spriteMat;
  vec4 smpColor = texture2D(u_texture, uv.xy / uv.z);

  gl_FragColor = smpColor;
}

The sample showing only the "6" frame

threejs: sprite animation, showing "6" by specifying the frame

2. Animate in a loop

Now we finally get to the animation. Here is the vertex shader from before with a few changes. The fragment shader stays the same.

On the JavaScript side, I added u_time (the current time from requestAnimationFrame) and u_startTime (the time the animation started) to the uniforms, and update u_time in the animation loop. The current frame is calculated from the difference between u_time and u_startTime, and the coordinate transform is updated to match.

uniform float u_time;
uniform float u_startTime;

varying vec2 v_uv;
varying mat3 v_spriteMat;
  
void main(void) {
  float elapsedTime = u_time - u_startTime;
        
  float colNum = 4.0;
  float rowNum = 4.0;
  float fps = 4.0;
  float frameNum = 16.0;  
    
  float frameIndex = floor(mod(elapsedTime * fps, frameNum));    
    
  mat3 scaleMat = mat3(
    1.0 / colNum, 0.0, 0.0,
    0.0, 1.0 / rowNum, 0.0,
    0.0, 0.0, 1.0
  );

  mat3 translateMat = mat3(
    1.0, 0.0, mod(frameIndex, colNum),
    0.0, 1.0, rowNum - (floor(frameIndex / colNum) + 1.0),
    0.0, 0.0, 1.0
  );    
    
  v_spriteMat = translateMat * scaleMat;
  v_uv = uv;
  
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
} 

3. Done!

And with that, the sprite image animation is done!!!!!!!

The finished result is at the link below, where you can also see the JavaScript-side changes mentioned above.

threejs: loop sprite animation

The finished loop sprite animation

Finally

KAYAC is very, very, very much looking for front-end engineers who want to write WebGL.

Tomorrow's article is by Gon, a front-end engineer who is a very senior colleague of mine.

Thank you!