In order to create a stand still sprite animation with Pygame we need to

Create a GameSprite object which will take in the spritesheet and processes it then return a surface of the sprite which can then be used in the screen.blit method. Create a rectangle object which will be used to clip the area of the spritesheet. Create a mechanism which will change the sprite image as well as only change to the new sprite image after x numbers of frame so the sprite will not change that fast on the screen!

Before we start make sure you have created your own spritesheet with each sprite consists of 64px width and 64px height. Below is the spritesheet I have used in this tutorial, I am only using six out of the seven sprite from below spritesheet because the last sprite which is the jumping sprite is not required in this tutorial.

Below is the GameSprite module which will be used in our next pygame module.

import pygame class GameSprite(object): def __init__(self, image, rect): self.image = image self.rect = rect self.sprite = pygame.image.load(image).convert_alpha() def getImage(self): # this method will return a subsurface which is a portion of the spritesheet self.sprite.set_clip(self.rect) # clip a portion of the sprite with the rectangle object return self.sprite.subsurface(self.sprite.get_clip())

We can use the above module in this next module to create a stand still animation sprite.

#!/usr/bin/env python import pygame from pygame.locals import * from sys import exit from vector2d import Vector2D from game_sorite import GameSprite robot_sprite_sheet = 'left.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) pygame.display.set_caption("Pygame Demo") w, h = 64, 64 # width and height of the sprite sprite_counter = 0 # initialize the sprite_counter game_frame = 0 # initialize the game_frame counter player_pos = Vector2D(320, 240) # initialize the position of the sprite while True: for event in pygame.event.get(): if event.type == QUIT: exit() screen.fill((205, 200, 115)) rect = Rect((sprite_counter * 64, 0), (64, 64)) # the rectangle object uses to clip the sprite area game_sprite = GameSprite(robot_sprite_sheet, rect) game_sprite_surface = game_sprite.getImage() # get the sprite surface player_draw_pos = Vector2D(player_pos.x-w/2, player_pos.y-h/2) screen.blit(game_sprite_surface, player_draw_pos) #increase the sprite counter after x numbers of frame if(game_frame % 30 == 0): sprite_counter += 1 if(sprite_counter > 5): sprite_counter = 0 game_frame += 1 pygame.display.flip()

If you run the above script then you will get the below outcome…

Reference:

1. http://stackoverflow.com/questions/10560446/how-do-you-select-a-sprite-image-from-a-sprite-sheet-in-python

2. The Vector2D module has already been mentioned in the previous post