开发者

pygame Collision Detection for a Cannonball

开发者 https://www.devze.com 2023-04-12 01:26 出处:网络
For the past week I have been working on a Cannon Game for class. Our current iteration is to add a target and collision detection. From my understanding pygame.draw functions return Rect objects. I a

For the past week I have been working on a Cannon Game for class. Our current iteration is to add a target and collision detection. From my understanding pygame.draw functions return Rect objects. I append these objects to a list and pass this list to my cannonball. Cannonball then uses that list to detect if it has hit anything. However I receive "if self.current_ball.Rect.collidelist(self.collision_objects) > -1: AttributeError: 'NoneType' object has no attribute 'Rect'" error.

    def draw(self, screen):  
        '''
        Draws the cannonball
        '''      
        self.current_ball = pygame.draw.circle(screen, color["red"],(round(self._x),round(self._y)), 5)
        return self.current_ball

    def move(self):
        '''
        Initiates the cannonball to move along its
        firing arc
        '''
        while self.active:
            prev_y_v = self.y_v
            self.y_v = self.y_v - (9.8 * self.time_passed_seconds)
            self._y = (self._y - (self.time_passed_seconds * ((prev_y_v + self.y_v)/2)))
            self._y = max(self._y, 0)
            self._x += (self.delta_x)
            #self.active = (self._y > 0)
            self.collision_detect()
            if self.collide == True:
                self.active = False

    def collision_detect(self):
        '''
        Detects if the current cannonball has collided with any object within the 
        collision_objects list. 
        '''
        if self.current_ball.Rect.collidelist(self.collision_objects) > -1:
            self.collide = True

I'm not quite sure if there is anything wrong with this code, or is it ac开发者_StackOverflow社区tually the issue with the collision_objects list?


Rect objects doesn't have Rect attributes. Try removing the .Rect attribute as follows:

def collision_detect(self):
    '''
    Detects if the current cannonball has collided with any object within the 
    collision_objects list. 
    '''
    if self.current_ball.collidelist(self.collision_objects) > -1:
        self.collide = True

There may be more than one problem here. As far as I could see self.current_ball should be a Rect object and there is nothing in the code you posted that suggests it receives "None".

If the correction above doesn't work, you may need to check the rest of the class code to check if you are calling the your self.draw() function properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号