Whenever I hit coins(collectibles) in my game they must disappear totally from the screen but that doesn't happen. After hitting it does disappear but it is still there which increases my score when I'm at the position of coins
Here's the code for checking collision :
# This function works for Coins Only
def coinsHit_or_not(self, hero, thecoin):
hit = pygame.sprite.collide_rect(hero, thecoin)
if hit:
thecoin.hit()
self.score += 2
and my Coin Class (it includes hit() function):
class Coins(pygame.sprite.Sprite):
coinsFadeAway = [pygame.image.load('CoinsFadeAway/CS1.png'), pygame.image.load('CoinsFadeAway/CS2.png'),
pygame.image.load('CoinsFadeAway/CS3.png'), pygame.image.load('CoinsFadeAway/CS4.png'),
pygame.image.load('CoinsFadeAway/CS5.png'), pygame.image.load('CoinsFadeAway/CS6.png'),
pygame.image.load('CoinsFadeAway/CS7.png'), pygame.image.load('CoinsFadeAway/CS8.png'),
pygame.image.load('CoinsFadeAway/CS9.png'), pygame.image.load('CoinsFadeAway/CS10.png'),
pygame.image.load('CoinsFadeAway/CS11.png')]
def __init__(self, x, y):
super().__init__()
self.x = x
self.y = y
self.coinTouched = False
self.coins = pygame.image.load('CoinOG_Small.png')
self.coinSpin = 0
self.rect = self.coinsFadeAway[0].get_rect().move(x, y)
def draw(self, window):
if not self.coinTouched:
window.blit(self.coins, (self.x, self.y))
if self.coinSpin < 11:
window.blit(self.coinsFadeAway[self.coinSpin], (self.x, self.y))
self.coinSpin += 1
elif self.coinSpin > 11:
self.coinTouched = False
def hit(self):
self.coinTouched = True
can anyone help me in figuring out how should I delete that coin sprite completely from the screen or a way around so that the coins disappear but score won't get increased when I stay at the coins position
Check for the collision only if the "Coin" was not hit yet:
def coinsHit_or_not(self, hero, thecoin):
if not thecoin.coinTouched:
hit = pygame.sprite.collide_rect(hero, thecoin)
if hit:
thecoin.hit()
self.score += 2
Or add a method to the class Coins
which does collision test:
class Coins(pygame.sprite.Sprite):
# [...]
def collide(self, hero)
if self.coinTouched:
return False
self.coinTouched = pygame.sprite.collide_rect(hero, self)
return self.coinTouched
def coinsHit_or_not(self, hero, thecoin):
if thecoin.collide(hero)
self.score += 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.