I am working on a billiards game using Python and PyMunk for the physics engine. I have a method in my Decision_Tree class called in_line_of_sight that is supposed to use ray casting to determine whether there is a clear path (i.e., no balls blocking) between two points (ball1 and ball2) on the table.
Here is my code:
def in_line_of_sight(self, ball1, ball2, radius):
direction = ball2 - ball1
direction_length = direction.length
slight_reduction = 10.5 # this can be adjusted according to your needs
# Normalize the direction vector
direction = direction.normalized()
# Reduce the length of the direction vector slightly to end it just before reaching ball2
end_point = ball1 + direction * (direction_length - slight_reduction)
# Raycast and check if it hits anything before reaching ball2
info = self.space.segment_query_first(ball1, end_point, radius, pymunk.ShapeFilter())
# If the raycast hit nothing, the line of sight is clear
return info is None
Here is how I use it:
def selection_method(self):
object_combinations = self.generate_all_possible_pairs()
self.get_all_object_coords()
clear_pairs = []
for object_pair in object_combinations:
obj1 = object_pair[0]
obj2 = object_pair[1]
initial_position = self.main_object.position
if self.check_line_of_sight(initial_position, obj1, 10) == True:
if self.check_line_of_sight(obj1, obj2, 10) == True:
difficulty = self.calculate_difficulty(initial_position, obj1, obj2)
if difficulty != math.inf:
clear_pairs.append([obj1, obj2, difficulty])
return clear_pairs
However, I'm facing an issue where the check_line_of_sight method consistently returns False regardless of whether the line of sight between obj1 and obj2 is actually clear. The segment_query_first function doesn't seem to correctly identify the situation in the simulation.
The arguments obj1 and obj2 passed to check_line_of_sight are the coordinates of the center of the objects (in the form of pymunk.Vec2d instances), and the radius is the radius of the objects (set to 10 in the above code). I'm struggling to understand why the segment_query_first function is not returning the expected results. Any insights or suggestions would be appreciated.