Reputation: 13
everyone. I have been trying to make a ray caster for a project, but I have been stuck with this problem; my code hangs when the angle value goes beyond 90 degrees. why is this happening? is there a solution? here is my code:
class Ray:
def __init__(self, depth, character, world_map):
self.depth = depth
self.character = character
self.map = world_map
def check_horizontal_offset(self, coordinate, sin, tan):
# if sin > 0, then character is pointing down. else, up.
if sin > 0:
offset_y = self.map.cell_size - (coordinate % self.map.cell_size) - 0.0001
else:
offset_y = -(coordinate % self.map.cell_size)
offset_x = offset_y / tan
hypotenuse = math.sqrt(offset_x ** 2 + offset_y ** 2)
return offset_x, offset_y, hypotenuse
def check_vertical_offset(self, coordinate, cos, tan):
# if cos > 0, character is pointing right, else left
if cos > 0:
offset_x = self.map.cell_size - (coordinate % self.map.cell_size) - 0.0001
else:
offset_x = -(coordinate % self.map.cell_size)
offset_y = offset_x * tan
hypotenuse = math.sqrt(offset_x ** 2 + offset_y ** 2)
return offset_x, offset_y, hypotenuse
def cast_ray(self, origin, sin, cos, tan):
ray_distance = 0
x, y = origin
while ray_distance < self.depth:
x_1, y_1, hypotenuse_1 = self.check_horizontal_offset(x, sin, tan)
x_2, y_2, hypotenuse_2 = self.check_vertical_offset(y, cos, tan)
if hypotenuse_1 < hypotenuse_2:
ray_distance += hypotenuse_1
print("hyp 1 ", hypotenuse_1)
x += x_1
y += y_1
else:
ray_distance += hypotenuse_2
print("hyp 2 ", hypotenuse_2)
x += x_2
y += y_2
pygame.draw.line(comms.screen, (255, 255, 0), self.character.get_position(), (x, y), 2)
def update(self, angle):
# calculate all trigonometric values for calculation of intersections
sin = math.sin(angle)
cos = math.cos(angle)
tan = math.tan(angle)
# safeguard for divide by zero error
if tan == 0:
tan = 0.000001
self.cast_ray(self.character.get_position(), sin, cos, tan)
Any help with this would be appreciated.
Upvotes: -1
Views: 20