Ray casting with Bresenham algorithm in PICO-8 (PICO-8でブレゼンハムアルゴリズム)

At first, I was supposed to implement a super light-weight 2d physics engine for PICO-8. But when I realized it, I was implementing the PICO-8 version of the Besenham algorithm.

元々はPICO-8向けの軽量2D物理エンジンを作成するつもりだったのですが、いつの間にかPICO-8版のブレゼンハムアルゴリズムを作成していました。

Bresenham Algorithm for PICO-8 (PICO-8用ブレゼンハムアルゴリズム)

The library is uploaded to the GitHub. The link is here:

ライブラリはGitHubに置いてあります。リンクはこちら。

github.com

Sample code (サンプルコード)

And here is the sample code:

こちらがサンプルコードになります。

do 
 local step=0
 
 local function drawpoint(x,y)
  local c=pget(x,y)
  if c==8 then
   circfill(x,y,2,9)
   return {x=x,y=y}
  elseif c~=0 then
   if step%3==1 then pset(x,y,9) end
  else
   pset(x,y,7)
  end
  step=step+1
 end
 
 function raycast(x1,y1,x2,y2,s)
  step=0
  los(x1,y1,x2,y2,drawpoint)
 end 
end

function _init()
 t1=0
 t2=0
end

function _update()
 y1=sin(t1)*64+64
 y2=sin(t2)*64+64

 t1=t1+0.005
 t2=t2+0.007
 
 if t1>1 then t1=t1-1 end
 if t2>1 then t2=t2-1 end
end

function _draw()
 cls()
 
 rectfill(0,0,20,30,1)
 rectfill(0,95,10,125,5)
 rectfill(15,60,35,110,2)
 rectfill(40,5,65,35,3)
 rectfill(50,50,90,80,4)
 rectfill(80,100,105,120,13)
 rectfill(100,5,127,30,5)
 rectfill(110,75,127,100,1)

 rect(25,10,35,20,8)
 rect(50,105,65,115,8)
 rect(80,-1,95,10,8)
 rect(100,45,110,70,8)
 rect(115,115,128,128,8)

 raycast(0,y1,127,y2)
end

In this sample, I made a ray casting function(raycast) with the line of sight (LOS) function of my library.

このサンプルでは、直線での障害物判定関数(raycast)をライブラリのLOS関数を利用して作成しています。

Output of the sample code (サンプルの動作結果)

Finally, this is the result of the sample code.

サンプルの動作結果です。

f:id:tkitao:20160922131826g:plain

Feel free to use it! BTW, I wonder when I can complete my physics engine.

ご自由にご利用ください! 本命の物理エンジンが完成するのはいつのことやら…。