Sprite Vertex Color Attribute


Setup

The vertexcolor.script sets the vertex attribute “mycolor”, which has been specified in the material.

vertex attribute material

The shaders specified by the material also makes use of the mycolor attribute to colorize the sprites.

The vertex attributes can also be animated. Click the image for an animation effect.

Scripts

vertexcolor.script

function init(self)
    msg.post(".", "acquire_input_focus")
    
    local scale = 0.75
    local spacingx = 160 * scale + 10
    local spacingy = 190 * scale + 10
    local startx = 40 + spacingx*0.5
    local starty = 40 + spacingy*0.5

    local maxy = 3
    local maxx = 4

    self.urls = {}
    for y = 0, maxy do
        for x = 0, maxx do
            local p = vmath.vector3(startx + x*spacingx, starty + y*spacingy, 0.5)
            local id = factory.create("#factory", p, nil, nil, vmath.vector3(0.8, 0.8, 1))
            local url = msg.url(nil, id, "sprite")
            table.insert(self.urls, url)
            
            go.set(url, "mycolor", vmath.vector4(x/maxx, y/maxy, 0, 1))
        end
    end

    self.updated = false
end

function update(self, dt)
    self.updated = true
end

function on_input(self, action_id, action)
    if action_id == hash("touch") and action.pressed and self.updated then
        for _, url in ipairs(self.urls) do
            go.animate(url, "mycolor", go.PLAYBACK_ONCE_PINGPONG, vmath.vector4(0, 0, 1, 1), go.EASING_LINEAR, .2)
        end
    end
end

vertexcolor.vp

uniform highp mat4 view_proj;

// positions are in world space
attribute highp vec4 position;
attribute mediump vec2 texcoord0;
attribute mediump vec4 mycolor;

varying mediump vec2 var_texcoord0;
varying mediump vec4 var_mycolor;

void main()
{
    gl_Position = view_proj * vec4(position.xyz, 1.0);
    var_texcoord0 = texcoord0;
    var_mycolor = mycolor;
}

vertexcolor.fp

varying mediump vec2 var_texcoord0;
varying mediump vec4 var_mycolor;

uniform lowp sampler2D texture_sampler;
uniform lowp vec4 tint;

void main()
{
    // Pre-multiply alpha since all runtime textures already are
    lowp vec4 tint_pm = vec4(tint.xyz * tint.w, tint.w);
    gl_FragColor = texture2D(texture_sampler, var_texcoord0.xy) * tint_pm * var_mycolor;
}

If you want to play with these examples, you can get the project on Github.

Do you want to see more examples? Why not write a few yourself and submit a pull request? We love contributions.

GITHUB