简体   繁体   中英

Pygame - Moving Sprites at Different Speeds

I am working on the mechanics of several sprites i am using. I am working on game that involves collecting coins. I have sprite image of a spinning coin. I created a class for the coin sprite and I wrote an update function which switches from one image sprite to the next. The coin is spinning but the problem I'm having is that it is spinning too fast. How can i slow dow the spinning of the coin? Any help would be greatly appreciated. Thanks!

Here is the coin class:

class coins (pygame.sprite.Sprite):
coin_spin_frames = []
def __init__(self, x, y):
    pygame.sprite.Sprite.__init__(self)
    sprite_sheet = SpriteSheet('stuff/coins_1.png')

    image = sprite_sheet.get_image(0, 0, 40, 42)
    self.coin_spin_frames.append(image)
    image = sprite_sheet.get_image(0, 42, 40, 42)
    self.coin_spin_frames.append(image)
    image = sprite_sheet.get_image(0, 84, 40, 42)
    self.coin_spin_frames.append(image)
    image = sprite_sheet.get_image(0, 130, 40, 42)
    self.coin_spin_frames.append(image)

    self.image = self.coin_spin_frames[0]

    self.rect = self.image.get_rect()

    self.rect.x = x
    self.rect.y = y
def update(self):
    if self.image == self.coin_spin_frames[0]:
        self.image = self.coin_spin_frames[1]
    elif self.image == self.coin_spin_frames[1]:
        self.image = self.coin_spin_frames[2]
    elif self.image == self.coin_spin_frames[2]:
        self.image = self.coin_spin_frames[3]
    elif self.image == self.coin_spin_frames[3]:
        self.image = self.coin_spin_frames[0]

First, determine how fast you want the coin to spin. Let's say you want it to take 2 seconds to make a complete loop.

The update() function can call time.time(), and mod it by the amount of time to make a loop, then divide that by the loop time. (123121213.2 % 2 = 1.2. 1.2 / 2 = 0.6). Now, display the image that is 60% of the way through the self.coin_spin_frames list. (int(len(self.coin_spin_frames) * 0.6))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM