大家好~我是鐵匠史密斯
今天我們終於要從「光如何前進」的推導,走到它的第一個實際應用 —— 決定牆壁的高度!
是的,接下來的程式碼,將把光線走過的距離,轉換成牆壁在螢幕上的高矮。
screen
上的高度在昨天的程式中,我們已經能計算 fDistanceToWall
(光從玩家出發到撞到牆的距離)。
接下來,讓我們加上兩個關鍵變數:nCeiling
:牆壁的頂端位置(從螢幕上方算下來的行數)nFloor
:牆壁的底端位置(從螢幕上方算下來的行數)
記得,計算機圖學中,垂直方向 y
是由上而下的
由先來一張示意圖,之後的推導會一直需要這張圖~:
簡單來說呢:
fDistance
越大 -> 牆壁高度變矮fDistance
越小 -> 牆壁高度越高nCeiling
與 nFloor
的位置是對稱分布的,以螢幕的垂直中心為基準nScreenHeight / 2
。接著,依照 screen
畫面的垂直位置 y
來渲染天花板、牆壁以及地板
y
小於 nCeiling
-> 渲染天花板 ' '
y
介於 nCeiling
與 nFloor
之間 -> 渲染牆壁 #
y
大於 nFloor
-> 渲染地板 ' '
for (int y = 0; y < nScreenHeight; y++)
{
if (y < nCeiling) // If the pixel is above the nCeiling -> should be ceiling
{
screen[y * nScreenWidth + x] = ' '; // Set to space
}
else if (y > nCeiling && y <= nFloor) // If the pixel is between the nCeiling and nFloor -> should be wall
{
screen[y * nScreenWidth + x] = '#'; // Set to wall character
}
else // If the pixel is below the nFloor -> should be floor
{
screen[y * nScreenWidth + x] = ' '; // Set to floor character
}
}