Issue
I have to hit boxes around my characters in a scrolling game, one around a zombie, and one around a ninja. They both follow the player and that is find, right now I need to find out how to check if they overlap, to check for collision.
I've read a few other stack overflow questions about this topic and the answers don't seem to be what I'm looking for. Any help would be appreciated. THANKS!!!
Here is a smaller version of my code:
class ninja(object):
def __init__(self, x, y, ninjawidth, ninjaheight):
self.x = x
self.y = y
self.ninjaheight = ninjaheight
self.ninjawidth = ninjawidth
self.hitbox = (self.x + 10, self.y + 10, self.ninjaheight - 10, self.ninjawidth - 10)
def draw(self):
mainninja.hitbox = (mainninja.x + 10, mainninja.y + 10, mainninja.ninjaheight - 15, mainninja.ninjawidth - 10)
pygame.draw.rect(win, (255,0,0), mainninja.hitbox,2) #here is the hitbox
class zombie(object):
def __init__(self, zombiewidth, zombieheight):
self.x = winwidth
self.y = 391
self.height = zombieheight
self.width = zombiewidth
def draw(self):
self.hitbox = (zombie.x + 55, zombie.y + 35, zombie.width - 55, zombie.height - 45)
pygame.draw.rect(win, (255,0,0), zombie.hitbox, 2) #here is other hitbox
mainninja = ninja(60, 400, 192, 192)
zombie = zombie(192, 192)
I just want a code or function to put in main loop to check for collision between zombie and ninja hit boxes.
Solution
Use a pygame.Rect
object for the .hitbox
attributes.
Note you should use the self
attribute in the methods of the class rather than the global namespace variables mainninja
and zombie
:
class ninja(object):
def __init__(self, x, y, ninjawidth, ninjaheight):
self.x = x
self.y = y
self.ninjaheight = ninjaheight
self.ninjawidth = ninjawidth
self.hitbox = pygame.Rect(self.x + 10, self.y + 10, self.ninjaheight - 10, self.ninjawidth - 10)
def draw(self):
mainninja.hitbox = pygame.Rect(self.x + 10, self.y + 10, self.ninjaheight - 15, self.ninjawidth - 10)
pygame.draw.rect(win, (255,0,0), mainninja.hitbox,2) #here is the hitbox
class zombie(object):
def __init__(self, zombiewidth, zombieheight):
self.x = winwidth
self.y = 391
self.height = zombieheight
self.width = zombiewidth
self.hitbox = pygame.Rect(self.x + 55, self.y + 35, self.width - 55, self.height - 45)
def draw(self):
self.hitbox = pygame.Rect(self.x + 55, self.y + 35, self.width - 55, self.height - 45)
pygame.draw.rect(win, (255,0,0), self.hitbox, 2) #here is other hitbox
mainninja = ninja(60, 400, 192, 192)
zombie = zombie(192, 192)
Then you can use .colliderect()
to check for a collision:
if mainninja.hitbox.colliderect(zombie.hitbox):
# [...]
Answered By - Rabbid76
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.