Scratch provides two blocks to perform color detection on the screen: <touching color (#ff0000)?> and <color (#00ff00) is touching (#ff0000)?>. These blocks return true when the sprite is touching the specified color on the screen. There is no block for directly reading the color of a pixel on the screen but it has been suggested.[1] The workaround is to check many different colors until a match is found, which this page will describe.

Uses

Color detection has a few uses:

Programming

Basic Script

Scratch uses 24-bit color so a naïve implementation would be to loop over all 16 million colors:

define get color // run without screen refresh
set [color v] to [0] // the result will be stored in this variable
repeat (16777215) // 256^3-1=16777215, the total number of colors possible minus one
  if <touching color (color)?> then // if it finds the color, the script stops
    stop [this script v]
  end
  change [color v] by (1) // increments the color each time through the loop
end
Note Tip: A custom block set to "run without screen refresh" will eliminate the delay caused by loops. It is unlikely to make this script instant but it will be a lot faster.

Color Sensitivity

The color detection blocks are unable to detect all 16 million colors. They only sense 16 different shades of blue and 32 different shades of red and green, allowing the loop iterations to be decreased considerably:

define get color // run without screen refresh
set [color v] to [0] // the result will be stored in this variable
repeat (32)
  repeat (32)
    repeat (16)
    if <touching color (color)?> then
      stop [this script v]
      end
    change [color v] by (16) // cycles through shades of blue
    end
    change [color v] by (1792) // cycles through shades of green
  end
  change [color v] by (458752) // cycles through shades of red
end

Binary Search

A further improvement can be made with the use of a binary search. By darkening the screen with a translucent sprite or pen, the colors can be adjusted in a way that allows them to be found in fewer guesses. See for example Binary Search Image Scanner.

See Also

References

Cookies help us deliver our services. By using our services, you agree to our use of cookies.