V
V
Valentine2018-08-10 11:06:56
Python
Valentine, 2018-08-10 11:06:56

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")

But there's a problem. The function executes the desired condition indefinitely until the player moves away from the object. And I need it (the condition) to be fulfilled only once and the next time, only after the player "collides" with the object again. I tried many options, for example with boolean variables, but I still found solutions. Thanks in advance for the help to everyone who responded.
The full source code for the game can be found on GitHub .

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Egor Davydov, 2018-08-10
@tregor

No option - use variable flag!
Rough algorithm:

ЕСЛИ коллизия_есть ТО
    ЕСЛИ переменная == false ТО
        переменная = true
        и тут какие то действия
ИНАЧЕ
    переменная = false

A
alihang, 2018-08-10
@alihang

Use variable key with true/false values

A
Alexander Fateev, 2018-08-25
@the_plain

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 question

Ask a Question

731 491 924 answers to any question