Parallax Backgrounds For Your Games

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

nice effect @coder!

Thanks

Very cool!

@Coder - nice graphics too

I think you can simplify the “diff” calculation in parallax to

    local x=(offset/s)%w +offset/s/w
    sprite(img,x,0,w,h)
    sprite(img,x-w,0,w,h)
    sprite(img,x+w,0,w,h)

Thanks, I need to learn about %

@Coder it’s simple as anything, if you do:

for i=1,100 do
 print(i%10)
end

it will print 0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9 etc so if you use 0-9 as your width, you’ll wrap it 10 times. Thats a very dull explanation but you get the idea.

The user and all related content has been deleted.

Please feel free, that’s why I post things like this :slight_smile:

The user and all related content has been deleted.