Log In  

function box(_x,_y,_w,_h)
 return{
 x=_x,
 y=_y,
 w=_w,
 h=_h
 }
end

function get_cols(a)
 local gx,gy=flr(a.x/8),flr(a.y/8)
 local ex,ey=flr((a.x+a.w-1)/8),flr((a.y+a.h-1)/8)

 local list={}
 for i=gx-1,ex+1 do
  for ii=gy-1,ey+1 do
   if fget(mget(i,ii),0) then
    add(list,box(i*8,ii*8,8,8))
   end
  end
 end

 return list
end

function collide(a,_dx,_dy,list,side)

 local ca={
  x=flr(a.x),
  y=flr(a.y),
  w=a.w,
  h=a.h
 }

 for i=1,#list do
  local v=list[i]

  if col(v,ca) then
   if _dx>0 then
    a.x=v.x-a.w
    side["right"]=true
   elseif _dx<0 then
    a.x=v.x+v.w
    side["left"]=true
   end

   if _dy>0 then
    a.y=v.y-a.h
    side["down"]=true
   elseif _dy<0 then
    a.y=v.y+v.h
    side["up"]=true
   end

  end

 end

end

--diss code expects that "a" have a
--dx and dy 

function move(a)

 local sides={
  ["left"]=false,
  ["right"]=false,
  ["up"]=false,
  ["down"]=false
 }
 local l=get_cols(a)

 a.x+=a.dx
 collide(a,a.dx,0,l,sides)
 a.y+=a.dy
 collide(a,0,a.dy,l,sides)

 if sides["up"] or sides["down"] then
  a.dy=0
 end 

 if sides["left"] or sides["right"] then
  a.dx=0
 end 

 return sides
end

function col(a,b)
 return not(
 (a.x>b.x+b.w-1)or
 (b.x>a.x+a.w-1)or
 (a.y>b.y+b.h-1)or
 (b.y>a.y+a.h-1)
 )
end

this is the code that i use for collisions with the map
is not perfect but it works

hehe

the code is based in the pygame way of doing collisions
probably not the best way of doing collisions in pico-8

but it works for me atleast

the way to use this, is to just call the move function
in a table that have dx and dy

dx="direction in the x-axis"
dy="direction in the y-axis"

and update dx and dy

i not a pico-8 expert so, i probably using a lot of tokens

P#141827 2024-02-23 18:27 ( Edited 2024-03-03 15:55)


[Please log in to post a comment]