Jump to content
  • entries
    295
  • comments
    862
  • views
    242,347

Mucking around with fragment / pixel shaders

EricBall

434 views

In my game there's a ball which rolls around the playfield. While SpriteKit is very cool with baked in physics and lighting, it's a 2D engine. So although it will rotate the 2D texture of the ball around the Z axis, that doesn't really convey the look of the ball rolling forward.

My original idea was to go with a flat shaded sphere and let the normal map lighting give the ball a more 3D look. Unfortunately the result was less than satisfying. But then I had an idea. What if the ball was a window into a larger texture. Moving the window would then suggest the rolling motion.

While doing some investigation into how to implement this idea, I stumbled into the idea of using a custom shader. In SpriteKit you can assign an OpenGL ES fragment (aka pixel) shader to a sprite which then renders the sprite. These shaders are written in a C style language which is then compiled at runtime into instructions executed by the GPU. There's all kinds of special instructions for dealing with vectors (e.g. RGBA and XYZ) & matricies (e.g. rotation).

So I bashed at it this weekend (ghods it's good to code sometimes) and managed to get it working! The shader does 3 things:
1. Return transparent for pixels outside of the ball
2. Move the center of the ball around the base texture (where the center is is tracked by the main program)
3. Warp the edges of the texture to "wrap" it around the ball

The one problem with using a custom texture is you lose the built-in normal map lighting. I'd like to add this in as well, but my first attempts didn't work out. So I've put that on the to-do later list as the current result is good enough for now.

Also, for some reason SpriteKit does the rotation step after the custom shader. It's one less thing to handle in my shader, although it probably causes some quality loss. (But I will need to account for it in the lighting step.)



0 Comments


Recommended Comments

There are no comments to display.

Guest
Add a comment...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...