Hi, I am creating a simple game. For a bit now I have been trying to add collision detection. I am trying to use the colliderect() function to detect the collision but I get the error
when using these lines to detect the collision
both white_rect and player have rect methods.
if you want it here is my full (though a bit simplified) code
thanks in advance!
AttributeError: 'rectangle' object has no attribute 'colliderect' Script terminated
when using these lines to detect the collision
if player.colliderect(white_rect):
screen.fill(BLACK)
both white_rect and player have rect methods.
if you want it here is my full (though a bit simplified) code
import pygame, sys
pygame.init()
def main():
class rectangle(pygame.sprite.Sprite):
def __init__(self, image_file, location):
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.location = location
self.currentX = location[0]
self.currentY = location[1]
class player(pygame.sprite.Sprite):
def __init__(self, location, speed, image_file):
self.image = pygame.image.load(image_file)
self.speed = speed
self.start_location = location
self.currentX = location[0]
self.currentY = location[1]
self.keydownA = False
self.keydownD = False
self.keydownSPACE = False
self.jumping = False
self.jumpY = location[1]
self.jump_direction = 1 # 1 = going up, 0 = going down
self.jumpspeed = 20
self.rect = self.image.get_rect()
def detectMoving(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
self.keydownA = True
if event.key == pygame.K_d:
self.keydownD = True
if event.key == pygame.K_SPACE:
self.keydownSPACE = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
self.keydownA = False
if event.key == pygame.K_d:
self.keydownD = False
if event.key == pygame.K_SPACE:
self.keydownSPACE = False
def move(self):
if self.keydownA == True:
self.currentX -= self.speed
if self.keydownD == True:
self.currentX += self.speed
def jump(self):
if self.jumping == False:
self.jumpY = self.currentY
if self.keydownSPACE == True:
self.jumping = True
if self.jumping == True:
self.currentY -= self.jumpspeed
self.jumpspeed -= 1
if self.currentY == self.jumpY:
self.jumping = False
self.jumpspeed = 20
running = True
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
white_rect_sprite = ("white_rect.png")
player_sprite = ("player_sprite.png")
white_rect = rectangle(white_rect_sprite, (400, 480 - 130))
player = player([250, 480 - 145], 3, player_sprite)
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("My Platformer")
while running:
player.detectMoving()
player.move()
player.jump()
screen.fill(BLACK)
screen.blit(white_rect.image, (white_rect.currentX, white_rect.currentY))
screen.blit(player.image, (player.currentX, player.currentY))
#---------collision detection-----
if player.colliderect(white_rect):
screen.fill(BLACK)
pygame.display.flip()
main()
thanks in advance!