Mouse Control in Pico 8

Mouse Conrol and Collision Detection in PICO-8

What It Will Look Like

Code

The comments should explain a lot of what’s going on here!

-- point inside rectangle
-- @iiviigames | odd.codes
-- ██████████████

-- enable dev mode mouse and keyboard
poke(0x5f2d, 1)
-- mouse coordinates
mx, my = 90, 90 -- will be set to stat(32) & stat(33)
cursor = 1  -- mouse sprite
inside = false -- cursor inside bool
-- dimensions of cursor
cx, cy, cw, ch = 0,0,8,8

-- test box
box = {
 x=40,y=40,w=40,h=40,
 c1=12,c2=8,c=12,
 update=function(self)
  inside = click_region(box.x,box.y,box.w,box.h)
  self.c = inside and self.c1 or self.c2
 end,
 draw = function(self)
  rect(
   self.x,self.y,
   self.x+self.w,
   self.y+self.h,
   self.c
  )
 end
}

-->8
-- functionality

---@func click_region(x,y,w,h)
---@arg  {num} x  top left corner x component
---@arg  {num} y  top left corner y component
---@arg  {num} w  added to x to make right boundary
---@arg  {num} h  added to y to make bottom boundary
---@desc checks if mouse is within a rectangular region
---      needs to be called within an update function
---@ret	{bln}
function click_region(x,y,w,h)
 -- make sure you set cursor position to mouse position before this 
 local mx, my = mx, my
 local mw, mh = cw, ch
 
 -- horizontal check
 local xin = 
  not (x > mx) and -- left  side
  (x + w > mx)     -- right side 
  
 -- vertical check
 local yin =
  (y < my) and   -- top side
  not (y + h < my) -- bottom side
    
 -- as long as xin/yin are true, we are within a clickable region
 return xin and yin
end

-->8
-- main loop
function _update60()
 box:update()
 mx, my = stat(32), stat(33)
 
end

function _draw()
 cls()
 -- draw mouse cursor and the box
 spr(1,mx,my)
 box:draw()
 -- show some data on screen
 print('mx: '..mx,0,100, 9)
 print('my: '..my,0,106, 11)
 print('inside: '..tostr(inside),0,112, 10)
end

Pico-8 Cart!

cart