Reputation: 37
so i wrote small game where you have to dodge things but then i saw colliderect function and i wantet to change hard coded collusion with simply colliderect code. i set it up but it didnt wokred so i tested it and created new pygame file!
import pygame
w=400;h=400
pygame.init()
root=pygame.display.set_mode((w,h))
pygame.display.set_caption('TEST SUBJECT')
def gameloop():
thing=pygame.image.load('unnamed.png')
th=thing.get_rect()
thing2=pygame.image.load('s.png')
th2=thing2.get_rect()
clock=pygame.time.Clock()
while 1:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
quit()
root.blit(thing,(w//2-50,h//2-60))
root.blit(thing2,(0,0))
if th.colliderect(th2)==1:
print('OK')
pygame.display.update()
clock.tick(15)
gameloop()
as you can say here colliderect returns 1 even tho two object doesnt hit each other.
Upvotes: 0
Views: 198
Reputation: 142631
They hit each other because you don't change th
and th2
.
It doesn't matter that you display it in different places.
Try
root.blit(thing, th)
root.blit(thing, th2)
and you see that they collide.
You have to change th.x
, th.y
or th2.x
, th.y
to change position and then th.colliderect(th2)
will work.
EDIT: full working example
import pygame
# --- constants --- (UPPER_CASE names)
WIDTH = 400
HEIGHT = 400
BLACK = ( 0, 0, 0)
FPS = 25
# --- main --- (lower_case names)
# - init -
pygame.init()
root = pygame.display.set_mode((WIDTH, HEIGHT))
root_rect = root.get_rect()
# - objects -
thing1 = pygame.image.load('ball-1.png')
thing1_rect = thing.get_rect()
thing2 = pygame.image.load('ball-2.png')
thing2_rect = thing2.get_rect()
# move things
thing1_rect.left = root_rect.left
thing1_rect.centery = root_rect.centery
thing2_rect.right = root_rect.right
thing2_rect.centery = root_rect.centery
# - mainloop -
clock = pygame.time.Clock()
while True:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# - updates (without draws) -
# move objects
thing1_rect.x += 5
thing2_rect.x -= 5
# check collisions
if thing1_rect.colliderect(thing2_rect):
print('Collision')
# - draws (without updates) -
root.fill(BLACK)
root.blit(thing1, thing1_rect)
root.blit(thing2, thing2_rect)
pygame.display.update()
# - FPS -
clock.tick(FPS)
ball-1.png
ball-2.png
Upvotes: 1