Cocos Creator 3.7 Playing-Card Perspective Shader with Vertex Offsets
This example uses Cocos Creator 3.7.2. Shader syntax and built-in assets may differ in other versions.
The original screenshots were hosted by a third party and are no longer available.
Understanding the vertex transformation
Start with a copy of Cocos Creator’s builtin-sprite.effect. Do not edit the engine’s original built-in file. Find:
| |
As a quick experiment, add the vertex’s Y coordinate to X:
The lower edge remains in place when its Y coordinate is zero, while the upper edge shifts. This demonstrates that a_position can be used to deform the sprite according to its screen-space height.
Make the top edge converge
Choose a convergence point near the upper center of a 1920 × 1080 canvas:
For each vertex, the horizontal displacement is the difference between its X coordinate and the target X, scaled by the ratio between the vertex height and the target height. Upper vertices move more than lower vertices, creating the perspective effect.
Use a different baseline
If the cards begin 100 pixels above the bottom of the canvas, subtract that baseline from the Y coordinate:
| |
Expose the values as material properties
Add the target point and baseline to the effect properties:
Use them in the vertex program:
| |
The fragment program can remain the standard sprite texture and alpha-test implementation.
Apply the effect
- Find
ui-sprite-material.mtl, copy it into your own assets folder, and assign the copy to the sprite’s Custom Material property. - Save the custom shader as an effect file such as
gradient.effect. - Set the copied material’s Effect property to that file.
- Enable USE TEXTURE; otherwise the sprite texture will not be displayed.
- Adjust
u_pointandu_startyuntil the cards have the desired perspective.