Endless scrolling background in AS3
In this tutorial you will learn how to create an endless scrolling background in Actionscript 3 where an image will continue looping. I have used an image of some building for this tutorial, but any image will work.
Endless scrolling background in AS3
Step 1
Open a new AS3 file and import your image onto the stage by selecting File > Import > Import to Stage.
Step 2
Convert your image into a movie clip (F8). Then give an appropriate name, select the top left registration point. And click the ‘Export for Actionscript’ checkbox and give the class name: ScrollBg. Once you have create the movie clip delete it from the stage.
Step 3
Add the following code in the Actions panel.
//The speed of the scroll movement.
var scrollSpeed:uint = 2;
//This adds two instances of the movie clip onto the stage.
var s1:ScrollBg = new ScrollBg();
var s2:ScrollBg = new ScrollBg();
addChild(s1);
addChild(s2);
//This positions the second movieclip next to the first one.
s1.x = 0;
s2.x = s1.width;
//Adds an event listener to the stage.
stage.addEventListener(Event.ENTER_FRAME, moveScroll);
//This function moves both the images to left. If the first and second
//images goes pass the left stage boundary then it gets moved to
//the other side of the stage.
function moveScroll(e:Event):void{
s1.x -= scrollSpeed;
s2.x -= scrollSpeed;
if(s1.x < -s1.width){
s1.x = s1.width;
}else if(s2.x < -s2.width){
s2.x = s2.width;
}
}
Step 4
Test your movie clip Ctrl + Enter.



10 comments:
thank you it's a nice tutorial but i just a question, i need my picture goes on the right side could you explain the script for this
@grafisto
Change the minus for a plus like below.
s1.x += scrollSpeed;
s2.x += scrollSpeed;
yes i've done this but the picture goes away and don't go back by the left, that's my problem. it's seems S2 don't followes anything, please ligt my darkness
Hi, nice tutorial. What if I wanted to somehow make it so the user could control the image with their mouse and arrow keys? Have you experimented with this idea?
Thank you so much for this tutorial, it's been a big help. I'm having a problem though. I'm getting a gap after a while during scrolling. I have already checked that my image tiles correctly and I've tried it with several other tiled images. Do you know why this might be happening?
@grafisto
Obviously, you need to change the conditional statements as well, like below. You may need to change the values of the offsets for the images you are using.
function moveScroll(e:Event):void{
s1.x += scrollSpeed;
s2.x += scrollSpeed;
if(s1.x > s1.width){
s1.x = -s1.width+10;
}else if(s2.x > s2.width){
s2.x = -s2.width+10;
}
}
@Kyle
Yes, this is possible.
@Frances
Try changing the offsets. The values in my code work for my image. Your image might be different.
Great tutorial..but how do I add static content over the scrolling background.
@Potsy
Try adding the content inside the image movie clip.
Post a Comment