如何解决3D控制台游戏距离检测无法正常工作
我正在尝试在python控制台中制作3D游戏。没有任何错误,但是当我运行它时,它没有显示任何内容(这很好),因为它没有在玩家视图中检测到任何块(#)(不好)。
问题可能出在第78行附近,该行始终为True
(在射线的第一次距离检查中),我不知道为什么(这是我的问题)。我当然会添加玩家移动和更复杂的地图。目前,播放器只是以硬编码的速度向右旋转。
import os
import time
import math
import threading
hardMap = [ #exists so I can edit it
["#","#","#"],["#",".","#"]
]
gameMap = "".join(["".join(hardMap[n]) for n in range(len(hardMap))])
notDone = True
playerX = 2
playerY = 2
playerA = 0 #player angle --> +1 turn right; -1 turn left
fov = 4
fov = math.pi / fov
depth = 20
fps = 30
screenWidth = 120
screenHeight = 40
os.system(f'mode con: cols={screenWidth} lines={screenHeight}')
screen = [" " for n in range(screenHeight * screenWidth)]
mapWidth = len(gameMap[0])
mapHeight = len(gameMap)
def printScreen(string):
os.system('cls')
time.sleep(0.01) # reduce flickering
for x in [string[i:i+screenWidth] for i in range(0,len(string),screenWidth)]:
print("".join(x))
while(notDone):
playerA = playerA + 0.01
startTime = time.time()
for x in range(screenWidth):
rayAngle = (playerA - fov / 2) + ((x / screenWidth) * fov)
distanceToWall = 0
hitWall = False
eyeX = math.sin(rayAngle)
eyeY = math.cos(rayAngle)
while not hitWall and distanceToWall < depth:
distanceToWall += 0.1
testX = int(playerX + eyeX * distanceToWall)
testY = int(playerY + eyeY * distanceToWall)
distanceBeforTheIf = distanceToWall
if testX < 0 or testX >= mapWidth or testY < 0 or testY>= mapHeight: #---------------THE PROBLEM------------
hitWall = True
distanceToWall = depth
with open("log.txt","a") as f:
f.write(f"angle: {playerA}\ndistanceToWall:{distanceToWall}\ndistanceBeforTheIf :{distanceBeforTheIf}")
elif gameMap[testY * mapWidth + testX] == "#":
hitWall = True
ceiling = int((screenHeight / 2.0) - (screenHeight / distanceToWall))
floor = screenHeight - ceiling
for y in range(screenHeight):
if distanceToWall <= depth / 4: shade = u"\u2591"
elif distanceToWall < depth / 3: shade = u"\u2592"
elif distanceToWall < depth / 2: shade = u"\u2593"
elif distanceToWall < depth / 1: shade = u"\u2588"
else: shade = " "
if y < ceiling:
screen[y * ceiling + x] = " "
elif y > ceiling and y <= floor:
screen[y * screenWidth + x] = shade
else:
screen[y * screenWidth + x] = " "
printScreen(screen)
time.sleep(max(1./fps - (time.time() - startTime),0))
解决方法
现在可以使用。 hardMap
以前被称为gameMap
,但由于需要1d数组,因此我对其进行了更改,但仍然可以轻松更改地图。我只是改变了:
mapWidth = len(gameMap[0]) mapHeight = len(gameMap)
至
mapWidth = len(hardMap[0]) mapHeight = len(hardMap)
感谢随机戴维斯!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。