Rendering#

Rendering in GameKit is simply attaching one or more $sprite component instances to an entity. The built-in $spriteRenderer system handles the rest.

While this is sufficient for most needs, this guide explores additional capabilities the engine provides.

Background Color#

You can change the default background color using the setClearColor function.

import { setClearColor } from "gamekit-engine/core/renderer";

setClearColor("#ff0000"); // Red background at full opacity
setClearColor("#00ff0080"); // Green background at half opacity

Post Processing Shaders#

GameKit supports post-processing fragment shaders written in GLSL (OpenGL Shader Language).

Loading a Shader#

Load a post-processing fragment shader using the loadShader function as shown below:

import { loadShader } from "gamekit-engine/core/renderer";

const vignetteShader = `#version 300 es
precision highp float;

in vec2 f_uv;

out vec4 color;

uniform sampler2D u_tex;
uniform float alpha;

float inner_radius = 0.0;
float outer_radius = 0.6;

void main() {
  float x = abs(f_uv.x - 0.5) * 1.0;
  float y = abs(f_uv.y - 0.5) * 1.0;
  float q = (1.0 - sqrt(x * x + y * y) / outer_radius) / (1.0 - inner_radius);
  color = texture(u_tex, f_uv) * vec4(1, 1, 1, q * alpha);
}`;

loadShader("vignette", vignetteShader);

In the above example, we've written a fragment shader which applies a vignette effect on the screen and loaded it with an id of "vignette".

Activating a Shader#

Activate a loaded post-processing shader using the setActivateShader function as shown below:

import { setActiveShader } from "gamekit-engine/core/renderer";

setActiveShader("vignette"); // Sets the vignette shader as the active post-processing shader
setActiveShader(null); // Deactive the currently activated shader

NB: Only one post-processing shader is active at a time

No screen shader Vignette screen shader

Configuring Shaders#

In GLSL, the uniform keyword allows you to pass values to your shader.

As an example, in our earlier vignette shader, there is an additional float uniform calledalpha, which controls the strength of the mask.

To set the value of a shader uniform, use the setShaderUniform function as show below:

import { setShaderUniform } from "gamekit-engine/core/renderer";

setShaderUniform("alpha", "float", 1.0);
setShaderUniform("vec2param", "vec2", 1.0, 2.0);
setShaderUniform("vec2vparam", "vec2v", new Float32Array([1, 2, 3, 4]));
...

Activate your desired shader before configuring a uniform value.

Next Steps#

In the next guide, we'll explore user interfaces in more detail.