我构建的 raycaster 本身运行良好,但在我添加纹理时出现问题。我只有 ~1-2fps 运行带有纹理的施法者,否则 >120fps。我对编程很陌生。所以我想要一些优化方面的帮助。
“列表”是从光线投射中获得的所有距离值。 “clist”是光线接触墙壁的 x 和 y 位置的模数。 look 是玩家正在看的上/下角度。
我删除了阴影和阴影,因为它更慢了
def disp(list , clist):
rayspace = ceil(WIDTH / len(list))
for i in range(len(list)):
top = round(HEIGHT / 2 + 12000/list[i] + (look))
bottom = round(HEIGHT / 2 - 12000/list[i] + (look))
if top > bottom:
tallness = top - bottom
else:
tallness = bottom - top
y = 0
j = bottom
while not(j == top):
y += HEIGHT/tallness
k = 0
while not(k == rayspace):
color = wallpaper.get_at((floor(clist[i]/rayspace + k * 2), floor(y)))
color = (color[0] , color[1] ,color[2] )
screen.set_at((round(i * rayspace) + k , j) , color)
k+=1
j+=1
我用 while 循环替换了我的 for 循环,删除了所有全局变量,并在导入时使用了“from”,这有点帮助,但它仍然非常慢
如果有任何需要澄清的代码,我很乐意提供帮助
一方面,如果计算的结果对于循环的每次迭代都是相同的,那么您不必在循环的每次迭代中都这样做,您只需要在循环之前执行一次环形。尝试类似的东西:
def disp(list , clist):
rayspace = ceil(WIDTH / len(list))
half_height = HEIGHT / 2
for i in range(len(list)):
top = round(half_height + 12000/list[i] + (look))
bottom = round(half_height - 12000/list[i] + (look))
if top > bottom:
tallness = top - bottom
else:
tallness = bottom - top
y = 0
j = bottom
delta_y = HEIGHT / tallness
clist_i_div_rayspace = clist[i] / rayspace
round_i_mul_rayspace = round(i * rayspace)
while not(j == top):
y += delta_y
k = 0
floor_y = floor(y)
while not(k == rayspace):
color = wallpaper.get_at((floor(clist_i_div_rayspace + k * 2), floor_y))
color = (color[0] , color[1] ,color[2] )
screen.set_at((round_i_mul_rayspace + k , j) , color)
k+=1
j+=1
也是
not(j == top)
应该比j != top
快?