Just drawing a grid of rects?

I'm just trying to draw a super simple grid of sprites using drawRect. However, only the corner rects actually draw all four sides. Something happens with the other rects, making them appear 4x bigger than they actually (?) are.

Here's the code. I'm new to Lua (but old to programming)… this is just my first attempt at drawing something the code is "inspired" by the pachinko example.

function drawBlock(s, x, y, w, h)
  gfx.setColor(gfx.kColorBlack)
  gfx.setLineWidth(1)
  gfx.setStrokeLocation(gfx.kStrokeInside)
  gfx.drawRect(x, y, w, h)
end

function newBlock(x, y)
  local w = 40
  local h = 20
  local block = gfx.sprite.new()
  block.draw = drawBlock
  block:moveTo(x, y)
  block:setSize(w, h)
  block:setCollideRect(1, 1, w-2, h-2)
  block:add()
end

blocks = {}
local i = 0

local xs = {}
for x=0,400,40 do
  for y=0,240,20 do
    blocks[i] = newBlock(x, y)
    i += 1
  end
end

function playdate.update()
  gfx.sprite.update()
end

Doh. Just realized the origin of a sprite is it's center!

1 Like

yep, moveTo() sets the position of the center of the sprite, which you can change with sprite:setCenter(). One weird thing that someone pointed out recently is that the drawing origin is always the top left. :confused: I'd change that to match the sprite position, but it'd break too much existing code at this point. Oh well. One other thing to note is the (x,y,w,h) argument to the draw function is the subrect of the sprite bounds that needs to be repainted, and it might not be the entire sprite. (e.g. if another sprite moves in front of it but nothing causes the block sprite to refresh.) In your example above, you'll want to do gfx.drawRect(0,0,s:getSize()) instead.

I always found having the sprite centre default to .5, .5 odd for the same reason. Most everything is done by the top left coord. It's no biggy but I guess I lose a few CPU cycles setting the sprite origin every time after making it

It gets me every time, too. :confused: It used to be top left but then we had a debate and a vote, back in the Days of the Ancient Developers, and the centrists won. And now we live in the shadow of their folly.

4 Likes