Skip to content Skip to sidebar Skip to footer

How Do I Display A Large Black Rectangle With A Moveable Transparent Circle In Pygame?

That question wasn't very clear. Essentially, I am trying to make a multi-player Pac-Man game whereby the players (when playing as ghosts) can only see a certain radius around th

Solution 1:

The best I can think of is kind of a hack. Build an image outside pygame that is mostly black with a circle of zero-alpha in the center, then blit that object on top of your ghost character to only see a circle around it. I hope there is a better way but I do not know what that is.

Solution 2:

If you only want to show the scene inside a circular area, then you can do the following:

  • Clear the display.

  • Limit the drawing region to a square area around the circular area

  • Draw the scene

  • Draw a transparent circle surface on top of the square area

The circle surface can be created with ease on runtime. Define the radius of the circular area (areaRadius). Create a square pygame.Surface with the doubled radius of the circular area. Fill it with opaque black and draw a transparent circle in the middle:

circularArea = pygame.Surface((areaRadius*2, areaRadius*2), pygame.SRCALPHA)
circularArea.fill((0, 0, 0, 255))
pygame.draw.circle(circularArea, (0,0,0,0), (areaRadius, areaRadius), areaRadius)

The drawing region of a surface can be limited by .set_clip(). Calling the function with the parameter None removes the clipping area. In the following screen is the surface which represents the window and areaCenter is the center of the circular area on the screen:

while run:

    # [...]# remove clipping region and clear the entire screen
    screen.set_clip(None)
    screen.fill(0)

    # set the clipping region to square around the circular area
    areaTopleft = (areaCenter[0]-areaRadius, areaCenter[1]-areaRadius)
    clipRect = pygame.Rect(areaTopleft, (areaRadius*2, areaRadius*2))
    screen.set_clip(clipRect)

    # draw the scene# [...]# draw the transparent circle on top of the rectangular clipping region
    screen.blit(circularArea, areaTopleft)  

    # clear the dripping region and draw all the things which should be visible in any case
    screen.set_clip(None)
    # [...]

    pygame.display.flip()

Post a Comment for "How Do I Display A Large Black Rectangle With A Moveable Transparent Circle In Pygame?"