I tried to make some code run when two boxes collide with each other in Pygame, but somehow it is not working.
Game Declarations
class coin:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.x2 = x + width
self.y2 = y + height
self.height = height
self.width = width
x = 50
y = 50
width = 20
height = 20
x2 = x + width
y2 = y + height
vel = 10
newCoin = coin(0,0,0,0)
needCoin = True
def generateCoin():
randX = math.floor(random.random() * 100)
randY = math.floor(random.random() * 100)
print(randX)
print(randY)
return coin(randX, randY, 10, 10)
Game Display
if ((x < newCoin.x2) and (newCoin.x < x2) and (y2 > newCoin.y) and (newCoin.y2 > y)):
print("Colliding")
needCoin = True
pygame.time.delay(100)
pygame.draw.rect(win, (0,255,0), (newCoin.x,newCoin.y,newCoin.width,newCoin.height))
pygame.display.update()
I recommend to use pygame.Rect
and .coliderect()
:
coin_rect = pygame.Rect(newCoin.x, newCoin.y, newCoin.width, newCoin.height)
rect_2 = pygame.Rect(x, y, width, height)
if coin_rect.colliderect(rect_2):
print("Colliding")
needCoin = True
pygame.time.delay(100)
If you want to make your code work, then you have to ensure that self.x2
, self.y2
respectively x2
and y2
is up to date. That you have to update this variables when ever self.x
, self.y
respectively x
, y
changes.
Anyway I recommend to use pygame.Rect
instead of x
, y
, width
and height
:
class coin:
def __init__(self, x, y, height, width):
self.rect = pygame.Rect(x, y, height, width)
def generateCoin():
randX = math.floor(random.random() * 100)
randY = math.floor(random.random() * 100)
print(randX)
print(randY)
return coin(randX, randY, 10, 10)
test_rect = pygame.Rect(50, 50, 20, 20)
vel = 10
newCoin = generateCoin()
needCoin = True
if newCoin.rect.colliderect(test_rect):
print("Colliding")
needCoin = True
pygame.time.delay(100)
pygame.draw.rect(win, (0,255,0), newCoin.rect)
pygame.display.update()