Here’s a simple function for drawing endlessly scrolling parallax backgrounds. To use it just call:
parallax(amount,Offset,Image)
•Amount is the amount the background scrolls(1 is normal speed(close up) 10 is 10 times slower(far away))
•Offset is the amount the screen is offset or the distance the player has moved from its starting position
•Image is the image to tile across the background
Here is an example of the code in use: ~~~ -- Main supportedOrientations(CurrentOrientation) displayMode(FULLSCREEN) function setup() playerX=0 tint(0,200,0) bigHills=makeImg("Platformer Art:Hill Tall",60) noTint() smallHills=makeImg("Platformer Art:Hill Short",50) mushrooms=makeImg("Platformer Art:Mushroom") txt=image(WIDTH,HEIGHT) setContext(txt) fill(255) textMode(CENTER) textAlign(CENTER) fontSize(100) font("Arial-BoldMT") text("Tilt to move",WIDTH/2,HEIGHT-100) setContext() end
function draw()
playerX = playerX +Gravity.x*20
background(0)
spriteMode(CORNER)
parallax(4,playerX,“SpaceCute:Background”)
parallax(3,playerX,bigHills)
parallax(2,playerX,smallHills)
parallax(1,playerX,mushrooms)
parallax(2.5,playerX,txt)
sprite(“Platformer Art:Guy Standing”,WIDTH/2,0)
end
function parallax(s,offset,img)
local w,h=spriteSize(img)
if h~=HEIGHT then
local sf=w/h
local sf2=HEIGHT/h
h=HEIGHT
w = sf*h
end
local diff=-offset/s
local r=diff/w–WIDTH
diff = diff - math.floor(r)*w–WIDTH
sprite(img,r+diff,0,w,h)
sprite(img,r+diff-w–WIDTH
,0,w,h)
sprite(img,r+diff+w–WIDTH
,0,w,h)
end
function makeImg(spr,size,n)
local img=image(WIDTH,HEIGHT)
setContext(img)
spriteMode(CORNER)
local w=size or spriteSize(spr)
for i=1,n or 10 do
sprite(spr,math.random(0,WIDTH-(w+20)),0,math.random(w-20,w+20))
end
setContext()
return img
end
if you can think of a better way to do this, find it useful or have a suggestion please comment below