Python Forum
[PyGame] Keeping the player within a polygon
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Keeping the player within a polygon
#5
If you use this function, it will give you the list of points that makeup your boundary.

def cast_ray(start, end):
    start_x, start_y = start
    end_x, end_y = end
    # y = mx + b
    # or, using words since we're not barbarians...
    # y = (slope * x) + y_intercept

    # add a small nudge to x, to avoid dividing by zero
    x_diff = start_x - end_x + 0.01
    slope = (start_y - end_y) / x_diff
    #    print(start, end, slope)
    # y_intercept = y - (slope * x)
    y_intercept = start_y - (slope * start_x)

    points = set()
    min_x = min(start_x, end_x)
    max_x = max(start_x, end_x)
    #  print(min_x, max_x, y_intercept)
    for x in range(min_x, max_x):
        y = (slope * x) + y_intercept
        points.add((x, round(y)))

    min_y = min(start_y, end_y)
    max_y = max(start_y, end_y)
    for y in range(int(min_y),int(max_y)):
        x = (y - y_intercept) / slope
        points.add((round(x), y))
    return list(points)
Give your player a pygame.Rect(), and then loop over the list to see if those points are within the player rect.
for point in list_of_points:
    if player_rect.collidepoint(point):
        collision = True
metulburr and Atekka like this post
Reply


Messages In This Thread
Keeping the player within a polygon - by Atekka - Feb-27-2021, 12:16 AM
RE: Keeping the player within a polygon - by Atekka - Feb-28-2021, 11:44 PM
RE: Keeping the player within a polygon - by michael1789 - Mar-02-2021, 02:52 AM
RE: Keeping the player within a polygon - by Atekka - Mar-06-2021, 10:28 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020