Issues with z-index when drawing geometry and text

Hey folks, I'm getting some confusing behavior while trying to draw some geometry and text for a UI menu. I'm using the :draw method of a sprite to draw a rectangle background, and then I'm drawing some menu options (a subclass of gfx.sprite that I made) over it. They appear correctly for a split second, and then vanish behind the rectangle, even though I'm setting their z-index to a higher value. Ex:
glitch

My code looks like this:

  local warningSprite = gfx.sprite.new()
  warningSprite:setBounds(0, 0, 400, 240)
  warningSprite:setZIndex(2)
  function warningSprite:draw()
    local margin = 48
    local padding = 4
    local text = 'Are you sure you want to start a\nnew game? Any progress will be lost.'
    gfx.setColor(gfx.kColorWhite)
    local height = 240 - margin * 2
    gfx.setClipRect(margin, margin, 400 - margin * 2, height)
    gfx.fillRect(margin, margin, 400 - margin * 2, height)
    gfx.setColor(gfx.kColorBlack)
    gfx.fillRect(margin + 1, margin + 1, 398 - margin * 2, height - 2)
    gfx.setImageDrawMode(gfx.kDrawModeFillWhite)
    gfx.drawText(text, margin + padding * 2, margin + padding * 2)
    gfx.setImageDrawMode(gfx.kDrawModeCopy)
  end
  warningSprite:add()
  
  local cancel = MainMenuOption(200, 120, 'CANCEL')
  local confirm = MainMenuOption(200, 140, 'OK')
  cancel:setActive(true)
  confirm:setActive(false)

And this is the entirety of the code for the MainMenuOption class:

local pd <const> = playdate
local gfx <const> = pd.graphics

class("MainMenuOption").extends(gfx.sprite)

function MainMenuOption:init(x, y, text)
  self:setBounds(0, 0, 400, 240)
  function self:draw()
    gfx.setImageDrawMode(gfx.kDrawModeFillWhite)
    gfx.drawText("*"..text.."*", x, y)
    gfx.setImageDrawMode(gfx.kDrawModeCopy)
  end
  self:setZIndex(3)
  self:add()

  self.cursorSprite = gfx.sprite.new(gfx.image.new('images/ui/cursor'))
  self.cursorSprite:setCenter(1, 0)
  self.cursorSprite:setZIndex(3)
  self.cursorSprite:moveTo(x - 12, y + 2)
  self.cursorSprite:add()
  self.cursorSprite:setVisible(false)
end

function MainMenuOption:setActive(active)
  self.cursorSprite:setVisible(active)
end

Am I missing something here? Does putting the geometry logic in :draw do anything that might override the z-index settings somehow?

This feels familiar, maybe

Figured it out! It was this line, which I had copied from somewhere else and didn't need:

gfx.setClipRect(margin, margin, 400 - margin * 2, height)

2 Likes