Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Shaders in behaviors

A behavior can run a shader. USE SHADER inside a BEHAVIOR puts the shader on any sprite that has the behavior, for as long as it has it.

SCREEN 320, 240
SHADER "stone"
    WHEN DRAWING
        c = IMAGE
        g = c.r * 0.3 + c.g * 0.59 + c.b * 0.11
        SET COLOR = RGBA(g, g * 0.95, g * 0.9, c.a)
    END WHEN
END SHADER

BEHAVIOR "petrified"
    USE SHADER "stone"
END BEHAVIOR

LOADIMG "hero.png", "hero"
ENABLE SPRITE 0
SET SPRITE 0 !! image("hero") x(140) y(100) scale((3, 3))
    !! behavior("petrified")
SHOW SPRITE 0
PAUSE

Turned to stone. That’s the same as !! shader("stone") on the sprite, but it travels with the behavior: a pattern that gives a sprite "petrified" gives it the look, too.

Moving a setting

What makes a behavior worth it is that it can move one of the shader’s settings for you, from one value to another over some ticks:

SCREEN 320, 240
SHADER "flash"
    USE NUMBER amount DEFAULT 0.0
    WHEN DRAWING
        c = IMAGE
        SET COLOR = MIX(c, RGBA(1.0, 1.0, 1.0, c.a), amount)
    END WHEN
END SHADER

BEHAVIOR "hit"
    USE SHADER "flash" !! param("amount") start(1) to(0) duration(20)
END BEHAVIOR

LOADIMG "hero.png", "hero"
ENABLE SPRITE 0
SET SPRITE 0 !! image("hero") x(140) y(100) scale((3, 3))
SHOW SPRITE 0
DO
    IF COOLDOWN(60)
        SET SPRITE 0 !! behavior("hit")
    END IF
LOOP

Once a second the hero is hit: it flashes white, and fades back to itself over 20 ticks.

  • param("amount") is the setting to move.
  • start(1) is where it starts, and to(0) where it ends.
  • duration(20) is how many ticks it takes.

Add !! loop and it goes there and back for as long as the sprite has the behavior, which is how a shield glows or a power-up that’s about to run out blinks:

SCREEN 320, 240
SHADER "flash"
    USE NUMBER amount DEFAULT 0.0
    WHEN DRAWING
        c = IMAGE
        SET COLOR = MIX(c, RGBA(0.4, 0.8, 1.0, c.a), amount)
    END WHEN
END SHADER

BEHAVIOR "shielded"
    USE SHADER "flash" !! param("amount") start(0) to(0.7) duration(30) loop
END BEHAVIOR

LOADIMG "hero.png", "hero"
ENABLE SPRITE 0
SET SPRITE 0 !! image("hero") x(140) y(100) scale((3, 3))
    !! behavior("shielded")
SHOW SPRITE 0
PAUSE

Crash-tan’s Tip: A behavior counts in ticks, and so the setting it moves keeps step with the game, not with the screen. A flash that takes 20 ticks takes a third of a second on any machine. That’s what to use when a shader effect has to line up with something in the game: a hit, a jump, a door opening.