Problem with pygame.Rect.colliderect

Problem with pygame.Rect.colliderect

Postby kostik » Thu Aug 15, 2013 7:49 am

So Iam trying to collide two Rect object....but error occurs
collision = pygame.Rect.colliderect(mousecoords_rect,A_rect,False)
TypeError: Argument must be rect style object

Code: Select all
Spider_image = pygame.image.load("spider.png")
Spider_image_rect = Spider_image.get_rect()
mousecoords = pygame.mouse.get_pos()
mousecoords_rect = pygame.Rect(mousecoords[0],mousecoords[1],10,10)
collision = pygame.Rect.colliderect(mousecoords_rect,A_rect,False)
kostik
 
Posts: 13
Joined: Tue Apr 16, 2013 10:26 am

Re: Problem with pygame.Rect.colliderect

Postby Mekire » Thu Aug 15, 2013 9:07 am

If you were to do this with colliderect it would be something like this:
Code: Select all
mousecoords = pygame.mouse.get_pos()
mousecoords_rect.topleft = mousecoords
if spider_rect.colliderect(mousecoords_rect):
    print("collide")

However, pygame.Rect.collidepoint() is much more suited to this job.
Code: Select all
import os
import sys
import pygame as pg


class Spider(object):
    def __init__(self,location):
        self.image = pg.Surface((50,50)).convert()
        self.image.fill((255,0,0))
        self.rect = self.image.get_rect(center=location)

    def draw(self,surface):
        surface.blit(self.image,self.rect)


class Control(object):
    def __init__(self):
        os.environ["SDL_VIDEO_CENTERED"] = '1'
        pg.init()
        self.screen = pg.display.set_mode((500,500))
        self.screen_rect = self.screen.get_rect()
        self.clock = pg.time.Clock()
        self.done = False
        self.fps = 60.0
        self.spider = Spider(self.screen_rect.center)

    def event_loop(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                if self.spider.rect.collidepoint(event.pos):
                    print("Collision")

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.screen.fill(0)
            self.spider.draw(self.screen)
            pg.display.update()
            self.clock.tick(self.fps)


if __name__ == "__main__":
    run_it = Control()
    run_it.main_loop()
    pg.quit()
    sys.exit()
(Spider replaced with a filled red rectangle.)

-Mek
User avatar
Mekire
 
Posts: 1015
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan


Return to Game Development

Who is online

Users browsing this forum: No registered users and 1 guest