Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local Class = require("middleclass")
- local Balls = {}
- local Ball = Class("Ball")
- Ball.radius = 2
- function Ball:initialize()
- self.x = love.math.random() * love.graphics.getWidth()
- self.y = love.math.random() * love.graphics.getHeight()
- local angle = love.math.random() * math.pi * 2
- local speed = 30
- self.vx = speed * math.cos(angle)
- self.vy = speed * math.sin(angle)
- end
- function Ball:update(dt, index)
- self.x = self.x + self.vx * dt
- self.y = self.y + self.vy * dt
- self:checkWallCollision()
- self:checkBallCollisions(index)
- end
- function Ball:checkWallCollision()
- if (self.x < 0) then
- self.x = 0
- self.vx = self.vx * -1
- end
- if (self.x > love.graphics.getWidth()) then
- self.x = love.graphics.getWidth()
- self.vx = self.vx * -1
- end
- if (self.y < 0) then
- self.y = 0
- self.vy = self.vy * -1
- end
- if (self.y > love.graphics.getHeight()) then
- self.y = love.graphics.getHeight()
- self.vy = self.vy * -1
- end
- end
- function Ball:checkBallCollisions(index)
- for i = index + 1, #Balls do
- local other = Balls[i]
- local dx = other.x - self.x
- local dy = other.y - self.y
- local distanceSquared = dx * dx + dy * dy
- local combinedRadius = self.radius + other.radius
- local combinedRadiusSquared = combinedRadius * combinedRadius
- if distanceSquared < combinedRadiusSquared then
- local midX = (self.x + other.x) * 0.5
- local midY = (self.y + other.y) * 0.5
- local normalX = (self.x - midX) / combinedRadius
- local normalY = (self.y - midY) / combinedRadius
- self.x = midX + normalX * combinedRadius * 1.01
- self.y = midY + normalY * combinedRadius * 1.01
- other.x = midX - normalX * combinedRadius * 1.01
- other.y = midY - normalY * combinedRadius * 1.01
- self.vx, other.vx = other.vx, self.vx
- self.vy, other.vy = other.vy, self.vy
- end
- end
- end
- function Ball:draw()
- love.graphics.circle("fill", self.x, self.y, self.radius)
- end
- local function spawnBalls(amount)
- for i = 1, amount do
- table.insert(Balls, Ball())
- end
- end
- function love.load()
- spawnBalls(8000)
- end
- function love.update(dt)
- for i, ball in ipairs(Balls) do
- ball:update(dt, i)
- end
- end
- function love.draw()
- for _, ball in ipairs(Balls) do
- ball:draw()
- end
- love.graphics.print(love.timer.getFPS())
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement