I made a an intersection simulation where there is Vehicle and a rectangle in the middle to detect when the vehicle touch the rectangle.
The "detector" or rectangle is defined as follows:
DetL = pygame.Rect(565,300,250,250)
The Vehicle class is defined as follows:
class Vehicle(pygame.sprite.Sprite):
def __init__(self, lane, vehicleClass, direction_number, direction,):
pygame.sprite.Sprite.__init__(self)
self.lane = lane
self.vehicleClass = vehicleClass
self.speed = speeds[vehicleClass]
self.direction_number = direction_number
self.direction = direction
self.x = x[direction][lane]
self.y = y[direction][lane]
self.crossed = 0
vehicles[direction][lane].append(self)
self.index = len(vehicles[direction][lane]) - 1
path = "images/" + direction + "/" + vehicleClass + ".png"
self.image = pygame.image.load(path)
#I intend on drawing a rectangle on every vehicle for collision detection purposes,
#No error came up in line 153, but when i call Vehicle.rect on line 236 it says Vehicle
#has no attribute rect
self.rect = self.image.get_rect()
if(len(vehicles[direction][lane])>1
and vehicles[direction][lane][self.index-1].crossed==0):
if(direction=='right'):
self.stop = vehicles[direction][lane][self.index-1].stop
- vehicles[direction][lane][self.index-1].image.get_rect().width
- stoppingGap
elif(direction=='left'):
self.stop = vehicles[direction][lane][self.index-1].stop
+ vehicles[direction][lane][self.index-1].image.get_rect().width
+ stoppingGap
elif(direction=='down'):
self.stop = vehicles[direction][lane][self.index-1].stop
- vehicles[direction][lane][self.index-1].image.get_rect().height
- stoppingGap
elif(direction=='up'):
self.stop = vehicles[direction][lane][self.index-1].stop
+ vehicles[direction][lane][self.index-1].image.get_rect().height
+ stoppingGap
else:
self.stop = defaultStop[direction]
if(direction=='right'):
temp = self.image.get_rect().width + stoppingGap
x[direction][lane] -= temp
elif(direction=='left'):
temp = self.image.get_rect().width + stoppingGap
x[direction][lane] += temp
elif(direction=='down'):
temp = self.image.get_rect().height + stoppingGap
y[direction][lane] -= temp
elif(direction=='up'):
temp = self.image.get_rect().height + stoppingGap
y[direction][lane] += temp
simulation.add(self)
While the "Detector" function is defined as follows:
def detection():
if DetL.colliderect(Vehicle.rect):
print("test")
The detector function then is called just before the end of my code:
detection()
pygame.draw.rect(screen, (255,255,255),DetL)
pygame.draw.rect(screen, (255,255,255), Vehicle.rect)
pygame.display.update()
Main()
I'm at a loss here. I have tried replacing if DetL.colliderect(Vehicle.rect)
with if DetL.colliderect(Vehicle)
it won't work. i also tried if DetL.colliderect(Vehicle.image)
because i figured that self.rect places rectangle in self.image. But it seems that i'm wrong there.