Wednesday, February 19, 2014

Collision Detection and Zombie Chase - Lesson 7 in the Beginner Series


New video in the seven lesson beginner series focuses on a way to get a monster to chase the girl.  An important point here is the use of colliderect to detect when two rectangles hit each other.  Collision detection of two or more rectangles is the fundamental of shooter games.

In this example, I use two graphics for the Zombie to allow him to run left and right when he's facing the appropriate direction.  Since I'm using the same rectangle for both graphics, I just have one colliderect check.

 

    if player_rect.colliderect(zombie_rect):
        screen.fill(RED)

player_rect is the girl's rectangle.


The algorithm to chase the girl is shown below:
    # chase the girl
    if player_rect.centerx < zombie_rect.centerx:
        zombie_rect.centerx -= 1
        zombie_horiz = "left"
    elif player_rect.centerx > zombie_rect.centerx:
        zombie_rect.centerx += 1
        zombie_horiz = "right"
    if player_rect.centery < zombie_rect.centery:
        zombie_rect.centery -= 1
    elif player_rect.centery > zombie_rect.centery:
        zombie_rect.centery += 1

New to PyChildren, the drill-based Python learning curriculum for teenagers?  Check out the link below to get started learning Python from zero.

An eleven lesson video set is available.

Code repository on GitHub.

Download entire code repository as a Zipped file.




No comments:

Post a Comment