Rectangles and obstacles
In this tutorial you will see how to do collision detection using rectangles. When testing if two things have collided you need to consider how accurate you want to be. In this set of examples we are doing collision detection with rectangles which means, as we have a ball, it may not always look smooth.
Some sample code to try –
from pygame import *
init()
width = 640
height = 480
screen = display.set_mode((width, height)) # tuple
display.set_caption('Graphics')
animationTimer = time.Clock()
ball = Rect(100,200,40,40)
obstacle = Rect(270,190,100,100)
dx = 1 # how fast/direction in x
dy = 4 # how fast/direction in y
endProgram = False
# game loops
# check input
# Update positions / game logic
# draw frame
while not endProgram:
# Check input
for e in event.get():
if e.type == QUIT:
endProgram = True
# update position
ball.move_ip(dx,dy)
# border check
if ball.y < 0 or ball.y > height - 40 :
dy *= -1
if ball.x < 0 or ball.x > width - 40:
dx *= -1
# check collision with obstacle
if ball.colliderect(obstacle):
if ball.centerx <= obstacle.x or ball.centerx>=obstacle.x +100:
dx = dx * - 1
if ball.centery <= obstacle.y or ball.centery>=obstacle.y +100:
dy = dy * - 1
# draw stuff
screen.fill((100,100,200))
# circle
draw.ellipse(screen, (0,255,0), ball)
# draw obstacle
draw.rect(screen, (200,200,200), obstacle)
# limit to 30 frames per second
animationTimer.tick(100)
# update the screen!
display.update()
Helpful links
http://tech.pro/tutorial/1007/collision-detection-with-pygame
http://thepythongamebook.com/en:pygame:step018 – Using masks to perform collision detection (advanced)











