Skip to content
Advertisement

The draw polygon function in pygame doesn’t draw the correct amount of vertices

I am trying to create a function that draws a random triangle on the screen. I need to make sure that the triangle is at least somewhat on the screen (although it doesn’t have to be fully on the screen).

First I choose a random point with the range of the random numbers being the bounds of the screen, and then I choose two random points with a range that’s 250 pixels larger in every direction.

This way I am making sure that at least one point is on the screen, which means that the triangle would be somewhat visible no matter what.

Here is my code:

JavaScript

Here is the issue though. For some reason, most of the time it either doesn’t even draw a triangle, like this for example: not a triangle

or the polygon isn’t on the screen at all (not sure if it’s out of frame or just isn’t being drawn): empty

What am I doing wrong?

By the way if you want to see that everything else is written correctly here it the rest of my code:

JavaScript

Advertisement

Answer

They don’t take into account the offset to the top left position of the bounding box of your random polygon. You cannot draw the polygon in window coordinates. You draw the polygon on an surface that is exactly the size of the polygon. The polygon needs to be drawn in the coordinates system of surface. Between the top left of the screen and the top left of the surface is a translation:

JavaScript

So you need to move the polygon to the top left of the surface. You need to subtract the minimum coordinates from all the coordinates of the polygon:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement