Generate new object (class) on button (key) hit

I created class with animated circle and then I want to create same objects every time I hit keyboard button… Problem that when I hit button here is always same object and animation disappear when button release…
On buttons’s hit I need new objects, so if I hit button many times here is appear many animated objects and not disappear.

How I can achieve this?

My code example

class Circleclass:
    def __init__(self,x,y,r,start=0):
        self.radius = r
        self.x = x
        self.y = y
        self.start = 0
    
    def __bool__(self):
        return self.start == 1

    def ani(self):
        if (self.__bool__):
            op = 0
            while (op < 10 * frameCount/30):
                op = op + 1
            strokeWeight(op)
            stroke(0,op)
            circle(self.x,self.y,self.radius)
    
def setup():
    size(500,500)
    
def draw():
    background(255)

def keyPressed():
    if key == 'r' or key == 'R':
        i = Circleclass(200,100,100)
        bool(i)
        i.ani()

You can store each circle you instantiate in a list. Then, you loop through that list to draw the circles each frame:

...

circles = []

def draw():
    background(255)
    for c in circles:
        c.ani()

def keyPressed():
    global circles
    if key == 'r' or key == 'R':
        i = Circleclass(random(width), random(height), 100)
        circles.append(i)

Note that I randomized each new circle’s x-y coordinate (so they don’t all appear in the same place).

1 Like

Thnx @tabreturn, its working! But, animation doesnt start from beginning, it continues… every new circle start from previous animation in class… how can I reset animation on every new object (and not affect animation from old ones)?

You’re using the frameCount to control the width of every circle. Instead, use an instance-specific value, something like –

        ...
        self.op = 0
    
    def ani(self):
        self.op += 1
        strokeWeight(self.op)
        stroke(self.op)
        circle(self.x, self.y, self.radius)

...
1 Like

Beautiful! Thank you for clarifications, @tabreturn! :grinning:

1 Like