Guest User

ball.lua

a guest
Dec 15th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.41 KB | None | 0 0
  1. require('player')
  2.  
  3. Ball = {}
  4. setmetatable(Ball, {
  5.     __call = function(self, x, y, color, speed, dir, ascend)
  6.         ball = {
  7.             x = x,
  8.             y = y,
  9.             color = color,
  10.             speed = 5,
  11.             dir = 1,
  12.             ascend = math.random(-8, 8)
  13.         }
  14.         return setmetatable(ball, {__index = Ball})
  15.     end
  16. })
  17.  
  18. function Ball:spawn()
  19.     self.x = width/2
  20.     self.y = trueHeight/2
  21.     self.color = randColor()
  22.     self.speed = 3
  23.     self.dir = math.random(2)
  24.     self.ascend = math.random(-8, 8)
  25. end
  26.  
  27. function Ball:checkCollision()
  28.     -- Paddle collision
  29.     local leftCol = (self.x >= width-20 and self.y >= players[2].pos and self.y <= players[2].pos+64)
  30.     local rightCol = (self.x <= 20 and self.y >= players[1].pos and self.y <= players[1].pos+64)
  31.     if leftCol or rightCol then
  32.         self.ascend = math.random(-8, 8)
  33.         self.speed = math.random(6, 11)
  34.         if self.ascend < 0 then
  35.             self.ascend = self.ascend * -1
  36.         end
  37.         self.dir = leftCol and 2 or 1
  38.     end
  39.     -- Screen collision
  40.     if (self.y >= gfx.getHeight()) or (self.y <= 4) then
  41.         self.ascend = self.ascend * -1
  42.     end
  43. end
  44.  
  45. function Ball:move()
  46.     -- Update ball positions
  47.     self.x = (self.dir == 1) and (self.x + self.speed) or (self.x - self.speed)
  48.     self.y = self.y + self.ascend
  49.     self:checkCollision()
  50.     -- Spawn ball & add score
  51.     local offLeft, offRight = (self.x < 0), (self.x > width)
  52.     if offLeft or offRight then
  53.         players[offLeft and 2 or 1]:updateScore()
  54.         ball:spawn()
  55.         love.timer.sleep(1)
  56.     end
  57. end
Add Comment
Please, Sign In to add comment