python 3.x - Rect.colliderect cannot detect specific collision -


i trying make simple game, here full code:

import pygame pygame.locals import * pygame.init()  #define variables width, height = 940, 780 screen = pygame.display.set_mode((width, height)) grey = 87, 87, 87 white = 255, 255, 255 player = pygame.image.load("pics\goodcar.jpeg") keys = [false, false, false, false] playerpos = [0,40] green = 0,255,0 red = 255,0,0 color = red  x1 = 0 x2 = 40 y1 = 940 y2 = 100     #main program  while 1:      screen.fill(0)     road = pygame.draw.rect(screen, grey, (x1,x2,y1,y2), 0)     traffic_light = pygame.draw.circle(screen, white, (640,90), 40, 1)       screen.blit(player, playerpos)       car_rect = player.get_rect()       if traffic_light.colliderect(car_rect):     print("its working")        event in pygame.event.get():         if event.type==pygame.quit:             pygame.quit()             exit(0)          if event.type == pygame.keydown:             if event.key==k_right:                 keys[0]=true             elif event.key==k_left:                 keys[1]=true             elif event.key==k_down:                 keys[2]=true             elif event.key==k_up:                 keys[3]=true           if event.type == pygame.keyup:             if event.key==pygame.k_right:                 keys[0]=false             elif event.key==pygame.k_left:                 keys[1]=false             elif event.key==pygame.k_down:                 keys[2]=false             elif event.key==pygame.k_up:                 keys[3]=false         if keys[0]==true:         playerpos[0]+=3     elif keys[1]==true:         playerpos[0]-=3     elif keys[2]==true:         playerpos[1]+=3     elif keys[3]==true:         playerpos[1]-=3     pygame.display.update() 

at part checks if car collided traffic light, doesn't anything. iv'e tried using try statement, still doesn't work

look @ documentation surface.get_rect() does:

returns new rectangle covering entire surface. rectangle start @ 0, 0 width. , height same size image.

so rects never collide, since rect car starts @ 0, 0. easy fix set starting position (top , left) of car rect while calling get_rect().

change

car_rect = player.get_rect() 

to:

car_rect = player.get_rect(left=playerpos[0], top=playerpos[1]) 

(another way use sprite class, combines surface , rect.)


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -