Answer the question
In order to leave comments, you need to log in
How to perform an action when the player collides with an object only once?
Wrote a function to handle player collision with an object using the pygame module:
def collide(self, xvel, yvel, plantlist): #Проверяет столкновение игрока с растениями
for sprite in plantlist:
if collide_rect(self, sprite):
if isinstance(sprite, sunPlants):
print("sun")
if isinstance(sprite, shadowPlants):
print("shadow")
if isinstance(sprite, waterPlants):
print("water")
Answer the question
In order to leave comments, you need to log in
No option - use variable flag!
Rough algorithm:
ЕСЛИ коллизия_есть ТО
ЕСЛИ переменная == false ТО
переменная = true
и тут какие то действия
ИНАЧЕ
переменная = false
If the player has the ability to intersect with several objects, it makes sense to keep the objects in the list and then it will be possible to determine exactly when the player began interacting with any object
class Player(object):
def __init__(self):
self.colliders = list()
def collide(self, xvel, yvel, plantlist):
for plant in plantlist:
collide = collide_rect(self, plant)
if collide and plant in self.colliders:
# Выполняется каждый раз пока игрок пересечен с растением
pass
if collide and not plant in self.colliders:
self.colliders.append(plant)
# Выполняется только один раз при пересечении с растением
if not collide and plant in self.colliders:
self.colliders.remove(plant)
# Выполняется только один раз когда игрок перестает пересекаться с растением
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question