lordmauve / pgzero

A zero-boilerplate games programming framework for Python 3, based on Pygame.
https://pygame-zero.readthedocs.io/
GNU Lesser General Public License v3.0
527 stars 191 forks source link

Add a Distance Between function #325

Closed Wowfunhappy closed 6 months ago

Wowfunhappy commented 7 months ago

PyGame Zero's colliderect function produces unexpected results for actors with non-rectangular images. I have been purposefully selecting square-ish assets for students to use as a workaround, but this is fairly limiting.

As an alternative means of collision detection, could PyGame zero add a function which returns the distance between two actors? Students could then write code like:

if distancebetween(hazard, player) < XX:
    player_died()

The code for this function could be very simple. I sometimes give the following to students:

def distinceBetween(actor1, actor2):
    distance = ((actor1.x - actor2.x) ** 2 + (actor1.y - actor2.y) ** 2) ** 0.5
    return distance

However, the math involved is a little too difficult for my students to understand, and I really dislike giving magical incantations to kids. It would be much better if this was part of PyGame Zero.

lordmauve commented 6 months ago

It's in the standard library since Python 3.8, math.dist(). It should just be math.dist(actor1.pos, actor2.pos).

I also think this is great moment to introduce Pythagoras' Theorem. I guess that could be a little advanced for younger programmers but I think it's really nice that one of the first geometric theorems they will meet has an immediate application in games programming.