So I am trying to create a puzzle platformer game with Python and Pygame, but I'm having a little bit of trouble. How do I make a collision detecter when I am using a blitted image for the main character, not a rect image? I know that rect images have left, right, top and bottom pixel functions (which would be extremely useful for collision detection) but is there anything like that for a blitted image? Or would I just have to create a variable for x and y coordinates + the width/height of the image? I tried that using
import pygame, sys
from pygame.locals import *
WINDOWWIDTH = 400
WINDOWHEIGHT = 300
WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
catx = 0
caty = 0
catRight = catx + 100
catBot = caty + 100
moveRight = False
pygame.init()
FPS = 40 # frames per second setting
fpsClock = pygame.time.Clock()
# set up the window
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')
while True: # the main game loop
DISPLAYSURF.fill(WHITE)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key in (K_RIGHT, K_w):
moveRight = True
elif event.type == KEYUP:
if event.key in (K_RIGHT, K_w):
moveRight = False
if catRight == WINDOWWIDTH:
moveRight = False
if moveRight == True:
catx += 5
DISPLAYSURF.blit(catImg, (catx, caty))
pygame.display.update()
fpsClock.tick(FPS)
But the catImg just kept going right past the end of the window. What am I doing wrong? Thanks in advance.
To prevent the image from going off the right edge you need to compute the maximum value its x coordinate can have, and the make sure that value is never exceeded. So before the loop create a variable with the value in it:
CAT_RIGHT_LIMIT = WINDOWWIDTH - catImg.get_width()
And then in the loop check it:
if catx >= CAT_RIGHT_LIMIT:
moveRight = False
catx = CAT_RIGHT_LIMIT
if moveRight == True:
catx += 5
You can, of course, extend this idea to all the other edges.