Advertisement
Juaxix

Asteroides - Codea game - 10/10 - Stars.lua

Nov 7th, 2011
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.91 KB | None | 0 0
  1. -- This class draws the lines streaming past in the background
  2. -- of the game. We spawn and delete them in the self.lines table
  3.  
  4. ----------------------------------------------
  5. -- Star
  6. ----------------------------------------------
  7. Star = class()
  8. function Star:init(pos, vel)
  9.     self.position = pos
  10.     self.velocity = vel
  11. end
  12.  
  13. function Star:update()
  14.     self.position.x = self.position.x - self.velocity
  15. end
  16.  
  17. function Star:draw()
  18.     p = self.position
  19.     line(p.x-self.velocity,p.y,p.x,p.y)
  20. end
  21.  
  22. function Star:shouldCull()
  23.     -- Check if off the left of the screen
  24.     if (self.position.x - self.velocity) < 0 then
  25.         return true
  26.     end 
  27.  
  28.     return false
  29. end
  30.  
  31. ----------------------------------------------
  32. -- All stars
  33. ----------------------------------------------
  34. Stars = class()
  35.  
  36. function Stars:init()
  37.     self.minSpeed  = 6
  38.     self.speed     = 23
  39.     self.spawnRate = 1
  40.     self.stars     = {}
  41. end
  42.  
  43. function Stars:updateAndCull()
  44.     toCull = {}
  45.     for i,star in ipairs(self.stars) do
  46.         if star:shouldCull() then
  47.             table.remove( self.stars, i )
  48.         else
  49.             star:update()
  50.         end
  51.     end
  52.  
  53.  
  54. end
  55.  
  56. function Stars:update()
  57.     -- Create spawnRate lines per update
  58.     for i = 1,self.spawnRate do
  59.         -- Generate random spawn location
  60.         vel = math.random(self.minSpeed, self.speed)
  61.         spawn = vec2( WIDTH - vel, math.random(HEIGHT) )
  62.         table.insert(self.stars, Star(spawn, vel))
  63.     end
  64.  
  65.     -- Update and cull offscreen lines
  66.     self:updateAndCull()
  67. end
  68.  
  69. function Stars:draw()
  70.     self:update()
  71.     pushStyle()
  72.  
  73.     noSmooth()
  74.     stroke(179, 153, 180, 173)
  75.     strokeWidth(2)
  76.     lineCapMode(SQUARE)
  77.  
  78.     for i,star in ipairs(self.stars) do
  79.         star:draw()
  80.     end
  81.  
  82.     popStyle()
  83. end
  84.  
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement