KaeruCT

background class for a pysfml project

Oct 23rd, 2011
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. import sf
  2. import math
  3.  
  4. class Background ():
  5.     def __init__ (self, texture_id, game):
  6.        
  7.         self.texture_id = texture_id
  8.         self.game = game
  9.        
  10.         texture = self.game.resourcemanager.get(self.texture_id)
  11.         self.sprite = sf.Sprite(texture)
  12.         self.sprite.set_sub_rect((0, 0, texture.width, texture.height))
  13.        
  14.         # whether to tile the background
  15.         self.tile = True
  16.        
  17.         # whether the background is relative to the camera
  18.         self.fixed = True
  19.        
  20.         # how much to scroll relative to the camera
  21.         # for example, it will scroll at 10% of the camera speed
  22.         self.scroll = 0.1
  23.        
  24.         # x and y "speed" for auto scrolling
  25.         self.autoscroll = (1, 1)
  26.  
  27.     def render (self, t, dt):
  28.         topx = (self.game.view.center[0] - self.game.view.width/2) * self.scroll
  29.         topy = (self.game.view.center[1] - self.game.view.height/2) * self.scroll
  30.        
  31.         if self.tile:
  32.             self.sprite.x = topx
  33.             self.sprite.y = topy
  34.            
  35.             xrepeat = int(math.ceil(self.sprite.width/self.game.view.width) / self.scroll)
  36.             yrepeat = int(math.ceil(self.sprite.height/self.game.view.height) / self.scroll)
  37.  
  38.             xautoscroll = (t * self.autoscroll[0]) % self.sprite.width
  39.             yautoscroll = (t * self.autoscroll[1]) % self.sprite.height
  40.  
  41.             for y in range(-1, yrepeat):
  42.                
  43.                 for x in range(-1, xrepeat):
  44.                    
  45.                     # % so the sprite position "tiles" too
  46.                     self.sprite.x = int(topx + xautoscroll +
  47.                                      (x * self.sprite.width))
  48.                                      
  49.                     self.sprite.y = int(topy + yautoscroll +
  50.                                      (y * self.sprite.height))
  51.                    
  52.                     self.game.window.draw(self.sprite)
  53.         else:
  54.             self.sprite.x = topx
  55.             self.sprite.y = topy
  56.             self.game.window.draw(self.sprite)
  57.  
  58.  
Advertisement
Add Comment
Please, Sign In to add comment