I was only just introduced to Python and I am having a bit of trouble on detecting collision between two rectangles. I want a one rectangle to bounce off the other when they collide
Here is my code so far:
import pygame
import sys
from pygame.locals import *
pygame.init()
ww = 400
wh = 300
w = pygame.display.set_mode((ww,wh))
pygame.display.set_caption('OFK')
s = pygame.display.get_surface()
green = pygame.Color(152,251,152)
blue = pygame.Color(135,206,250)
white = pygame.Color(255,255,240)
clock = pygame.time.Clock()
background_file = 'ice-in-water.jpg'
background_image = pygame.image.load(background_file).convert()
rx = ww/2
ry = wh/2
rw = 30
rh = 20
px = ww/2
py = wh - 40
pw = 60
ph = 10
vdirection = -1
hdirection = 1
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
if event.type == KEYDOWN:
#print (event.key,event.unicode)
if event.key == 275:
px = px + 30
if px > ww - pw:
px = ww - pw
if event.key == 276:
px = px - 30
if px < 0:
px = 0
s.fill(green)
pygame.draw.rect(s,blue,(rx,ry,rw,rh),0)
pygame.draw.rect(s,white,(px,py,pw,ph),0)
#w.blit(background_image,(-80,0))
pygame.display.update()
#mx,my = pygame.mouse.get_pos()
#print ("x: ", mx, "y: ", my)
#print ("ry: ", ry, "wh: ", wh)
rx = rx + 1.5 * hdirection
if rx > ww - rw:
hdirection = -hdirection
if rx < 0:
hdirection = -hdirection
ry = ry + 1.5 * vdirection
if ry > ww:
rx = ww/2
ry = wh/2
vdirection = -vdirection
if ry < 0:
vdirection = -vdirection
I have tried finding tutorials on how to do this, but I can't understand very well. A little help would be appreciated.