Optimizing parallax star background
Posted: Sun Jan 02, 2011 1:09 pm
I have a parallax star background in my game, but drawing it takes a significant chunk of resources (I get 55% more FPS when I don't draw it).
Is there a more efficient way to do this, or some way to better optimize my code? I made it have random depths (and sizes) because I think it looks a lot nicer than a small number of static depths, but I'll sacrifice it if absolutely necessary.
(http://pastebin.com/kRrkUan0)
Is there a more efficient way to do this, or some way to better optimize my code? I made it have random depths (and sizes) because I think it looks a lot nicer than a small number of static depths, but I'll sacrifice it if absolutely necessary.
(http://pastebin.com/kRrkUan0)
Code: Select all
local starimage = love.graphics.newImage("images/star.png")
Background = class()
function Background:init(numstars) -- 120 stars normally
self.numstars = numstars
self.parallax = {}
self.colors = {
[1] = {255, 192, 192}, -- red
[2] = {255, 255, 255}, -- normal
[3] = {255, 255, 192}, -- yellow
[4] = {192, 192, 255}, -- blue
}
-- create stars
for i = 1, numstars do
local x, y = math.random(0, xres*1.2), math.random(0, yres*1.2)
local depth = math.random(50, 90)/100
local color = math.random(#self.colors)
local size = math.random(3,6)/10
table.insert(self.parallax, {x, y, depth=depth, color=color, size=size})
end
end
function Background:draw()
-- local variables = faster!
local starimage = starimage
local campos = camera.pos
local xres, yres = xres, yres
local xarea, yarea = xres*1.2, yres*1.2 -- want slightly larger area than screen so it's harder to notice repeated stars
for i, star in ipairs(self.parallax) do
-- calculate new positions
local x = (star[1]-campos.x*star.depth) % xarea
local y = (star[2]-campos.y*star.depth) % yarea
if x >= 0 and x <= xres and y >= 0 and y <= yres then
-- only draw if actually onscreen
local color = self.colors[star.color]
love.graphics.setColor(color[1], color[2], color[3], 128)
love.graphics.draw(starimage, x, y, 0, star.size, star.size, 4, 4)
end
end
end