I’m creating parallax background as a collection with:
- background_controller: with a bg_controller.script
- number of other bg objects with: sprites and bg.script:
bg_controller.script:
go.property("move_vertical", false)
function init(self)
BG_CTRL_URL = msg.url()
self.bgs = {}
self.speeds = {}
self.pos_y = go.get_position().y
end
function update(self, dt)
local cam_x = CAM_POS.x
local cam_y = CAM_POS.y
for _,bg in ipairs(self.bgs) do
go.set(bg.id, "position.x", (1-(0.1*bg.no))*cam_x)
if self.move_vertical then go.set(bg.id, "position.y", self.pos_y + 0.5*(1-(0.05*bg.no))*cam_y) end
if bg.speed ~= 0 then
local pos = go.get_position(bg.id).x
if self.speeds[bg.no] == nil then self.speeds[bg.no] = 0 end
self.speeds[bg.no] = self.speeds[bg.no] + bg.speed
go.set(bg.id, "position.x", pos + self.speeds[bg.no])
end
end
end
function on_message(self, message_id, message, sender)
if message_id == m.REGISTER then
table.insert(self.bgs, {id = message.id, no = message.no, speed = message.speed} )
end
end
function final(self)
BG_CTRL_URL = nil
end
You can check move_vertical property, if you want also vertical parallax effect.
bg.script:
go.property("no", 0)
go.property("speed", 0)
local m = require "messages" -- module with available messages, for convenience and pre-hashing
function init(self)
assert(self.no ~= 0, "Provide no of bg")
if self.no < 10 then
timer.delay(0.1, false, function()
msg.post(BG_CTRL_URL, m.REGISTER, {id = go.get_id(), no = self.no, speed = self.speed} )
end)
end
end
where m.REGISTER
is:
hash("register")
I do specify in each bg properties:
- No - is my arbitrary number of layer - closer to 0 are far layers, and closer to 10 are slower, closer layers (10 is a static layer - not moving)
- Speed - it is used for some constantly floating layers like clouds
All you need to do for this collection to work is to constantly save camera’s (or just hero’s) position in this global variable - CAM_POS
You can add as many different layers as you want