Feb-20-2022, 03:10 PM
(This post was last modified: Feb-20-2022, 03:10 PM by deanhystad.)
I found a brick collision algorithm I like better. Beak the move into x and y components. Do the x move first. Check for collisions. Undo the x move and do the y move. Check for collisions. If you have x collisions, reverse x direction. If you have y collisions reverse y direction. If you have any collisions, revert to the previous position.
# Check for collisions with bricks. x1, y1 = self.x, self.y # Current position x2, y2 = x1 + self.dx, y1 + self.dy # Next position # Is there a collision if we only move in x? if (xhits := pygame.sprite.spritecollide(self.at(x2, y1), self.bricks, False)): self.dx = -self.dx # Is there a collision if we only move in y? if (yhits := pygame.sprite.spritecollide(self.at(x1, y2), self.bricks, False)): self.dy = -self.dy hits = set(xhits) or set(yhits) # Using sets to prevent a brick from being hit twice if hits: # If there were collisions undo the move and update the bricks. self.at(x1, y1) for brick in hits: self.score += brick.hit() else: # Move ball self.at(x2, y2)Been playing with this for a while and I'm not experiencing any odd bounces or unexpected multiple hits.