How do I animate an object on canvas with a bind with an animation already "running"

Asked

Viewed 363 times

0

I was making a copy game of Space Invaders but when I went to do the "shot" of the ship, I came across a following problem :

inserir a descrição da imagem aqui

As seen in Gif, when I press the key, everything on the canvas "freezes" until the shot reaches the end, how do I solve this ? thanks in advance.

Excerpt from the code :

def Update (self):
    while True :
        self.Move_nave()
        self.root.update()
        self.root.after(30)

def Shot (self, event):
    self.a_0 , self.a_2 = int(self.c.coords (self.bola)[0]), int(self.c.coords (self.bola)[2])
    self.a_1, self.a_3 = int (self.c.coords(self.bola)[1]), int (self.c.coords(self.bola)[3])
    self.tiro = self.c.create_rectangle(self.a_0 + 10, self.a_1, self.a_2 - 10, self.a_3, fill = 'blue')
    for c in range (10):
        self.c.move(self.tiro, 0, -10)
        self.root.after(40)
        self.root.update_idletasks()
  • 2

    The problem has to do with for within the method Shot, that can’t be done that way to upgrade the shot. Instead it has to have a list of existing shots and go updating one by one on each frame. The ideal however is to provide a Minimum, Complete and Verifiable Example problem, so it is easy to show the solution.

  • But still, how will I wear two "afters" at the same time ?

  • Would have only one after for each update of the various components

  • But without the after of shot he will not animate the shot and simply appear when I press the key.

1 answer

0

You need a rewrite in your code.

When firing the shot, you can’t animate the shot completely to the end. Instead, you must create an object that stores the position of the shot, you can use a class for that, or just a simple structure like a tuple.

Next you need to add this structure that represents shooting to a list, can call tiros_atuais that will contain all the shots that are active at the moment.

At a certain single point of your code, you need to update all the elements of the game. Update the position of the ship and also any shots on the list tiros_atuais. So you’ll have one .after() only in his code - and he will do all updates that depend on your game’s time.

Finally, if the shot has reached its destination, remove it from the list tiros_atuais so that it stops being updated.

  • Could you post the code ? = P

  • @Tortaamolante I don’t have a code. As your code is incomplete I couldn’t run it here. Moreover this change would be a general overhaul to implement this different logic. I believe my answer is complete and clear enough, answering the question in its entirety, without the need for code to complete it. Try to implement the solution I proposed, and if you have problems, open a new question, more specific, with the code you tried to write following this logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.