How can I create a simple "slider" with Flash AS3 - actionscript-3

I'm trying to create a jQuery-like slider in Flash. I'm currently using the tween class to move an object's x position, but it's slightly buggy. I have to use flash because it's being incorporated into a brochure software that works best with Flash.
When I click on the right arrow button, the object moves to a new x position. When I click on the button again, it moves, but sometimes it jumps back to the current position. When I click on the left button, it sometimes overshoots the destination.
I can create a simple "click to go to next frame" type of scroller, but it wouldn't provide the same tween/scrolling effect.
This is the code I'm using:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var scrollTweenRight:Tween = new Tween(mc_scroll, "x", Strong.easeOut, mc_scroll.x, mc_scroll.x-1940, 3, true);
scrollTweenRight.stop();
var scrollTweenLeft:Tween = new Tween(mc_scroll, "x", Strong.easeOut, mc_scroll.x, mc_scroll.x+1940, 3, true);
scrollTweenLeft.stop();
// functions
function scrollRight(e:MouseEvent){
scrollTweenRight.start();
}
function scrollLeft(e:MouseEvent){
scrollTweenLeft.start();
}
// listeners
btn_right.addEventListener(MouseEvent.CLICK, scrollRight);
btn_left.addEventListener(MouseEvent.CLICK, scrollLeft);

Use some library like TweenLite/TweenMax/Tweener, the built in one is not too good (and pretty slow as well).
If you want to move in regular 'steps', do not use mc.x to determine the final position as that will be taken upon each click on the button. Always store the 'final' (desired) position in a var. Example:
var shouldMoveToX:Number = 0; //initial position value
var step:Number = 500;
function scrollLeft(e:MouseEvent):void {
shouldMoveToX += step;
//kill the tween if any - I dunno if this is necessary, I haven't used Tween class in ages
//start the tween, pass the final position as shouldMoveToX
}
EDIT:
Oh I see what the problem is now - you are passing the mc's X pos into the constructor of Tween and you actually never update it. The tween will always begin from this point. Put that into your scrollLeft/Right functions:
function scrollRight(e:MouseEvent){
scrollTweenRight.begin = mc_scroll.x;
scrollTweenRight.start();
}
What I wrote above still applies, always use the shouldMoveToX as final position, otherwise it will have irregular movement when fast clicking.
...so your full code should look something like this:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var scrollTweenRight:Tween = new Tween(mc_scroll, "x", Strong.easeOut, mc_scroll.x, mc_scroll.x, 3, true);
scrollTweenRight.stop();
var scrollTweenLeft:Tween = new Tween(mc_scroll, "x", Strong.easeOut, mc_scroll.x, mc_scroll.x, 3, true);
scrollTweenLeft.stop();
var step:Number = 100;
var shouldMoveToX:Number = mc_scroll.x;
// functions
function scrollRight(e:MouseEvent){
scrollTweenRight.begin = mc_scroll.x;
shouldMoveToX -= step;
scrollTweenRight.finish = shouldMoveToX;
scrollTweenRight.start();
}
function scrollLeft(e:MouseEvent){
scrollTweenLeft.begin = mc_scroll.x;
shouldMoveToX += step;
scrollTweenLeft.finish = shouldMoveToX;
scrollTweenLeft.start();
}
// listeners
btn_right.addEventListener(MouseEvent.CLICK, scrollRight);
btn_left.addEventListener(MouseEvent.CLICK, scrollLeft);

Related

as3 addChild into a generated triangle

Helly everyone! I'm trying to dynamically add (and later remove) some movieclips inside of a triangle. Simple movieclip inside of a movieclip ain't working (it's a square in the end). Drawing a triangle is simple, addChild method is crystal clear too. The tough part comes after. Here's the code I'm trying to develop:
btn_toys_2.confirm.addEventListener(MouseEvent.MOUSE_UP, confirmToys);
import flash.display.Graphics;
var point1:Point = new Point(466, 65);
var point2:Point = new Point(370, 540);
var point3:Point = new Point(570, 540);
var vertices:Vector.<Number> = Vector.<Number>([point1.x, point1.y, point2.x, point2.y, point3.x, point3.y]);
var triangle:Sprite = new Sprite();
triangle.graphics.beginFill(0x00ff00, 1);
triangle.graphics.drawTriangles(vertices);
triangle.graphics.endFill();
addChild(triangle);
function confirmToys(e:MouseEvent){
var toy:MovieClip = new shar_001;
triangle.addChild(toy);
toy.x = Math.random()*30;
toy.y = Math.random()*30;
}
The "toy" movieclip is for some reason placed outside the triangle (0-30 x axis and 0-30 y axis).
The important part is to make "toys" appear within a triangle, doesnt have to be a movieclip. A way around this would be great too!
Thanks in advance!
It is happening this way because you have made your triangles anchor point at zero. You did this when you did
addChild(triangle);
That will always put the added child at (0,0). The only reason you triangle doesn't appear there is because you have added a cushion of empty pixels by making your points be greater than zero. Instead, you will use
addChild(triangle);
triangle.x = 370;
triangle.y = 65;
The point you want the top left corner of your triangle to be at is (370, 65). You should make your triangle points be (96, 0), (0, 475), (200, 475). Now the top left corner of the triangle is at (0,0) on the stage. Now set the triangle to (370, 65) after adding the triangle to the stage. Now the triangles anchor point is still the top left corner of the triangle, not the stage, so when you add the toy, it will be in reference to the point you expect.
// let the minimum x and y be zero, and adjust the others relative to that.
var point1:Point = new Point(96, 0);
var point2:Point = new Point(0, 475);
var point3:Point = new Point(200, 475);
var toyArray:Array = new Array();
var vertices:Vector.<Number> = Vector.<Number>([point1.x, point1.y, point2.x, point2.y, point3.x, point3.y]);
var triangle:Sprite = new Sprite();
triangle.graphics.beginFill(0x00ff00, 1);
triangle.graphics.drawTriangles(vertices);
triangle.graphics.endFill();
addChild(triangle);
// position anchor point on stage
triangle.x = 370;
triangle.y = 65;
function confirmToys(e:MouseEvent){
var p:Point = new Point(Math.random()*triangle.width,Math.random()*triangle.height);
if (isInsideTriangle(Point1,Point2,Point3,p))
{
var toy:MovieClip = new shar_001;
triangle.addChild(toy);
toyArray.push(toy);
toy.x = p.x;
toy.y = p.y;
}
}
private function isInsideTriangle(A:Point,B:Point,C:Point,P:Point):Boolean {
var planeAB:Number = (A.x-P.x)*(B.y-P.y)-(B.x-P.x)*(A.y-P.y);
var planeBC:Number = (B.x-P.x)*(C.y-P.y)-(C.x - P.x)*(B.y-P.y);
var planeCA:Number = (C.x-P.x)*(A.y-P.y)-(A.x - P.x)*(C.y-P.y);
return sign(planeAB)==sign(planeBC) && sign(planeBC)==sign(planeCA);
}
private function sign(n:Number):int {
return Math.abs(n)/n;
}
Removing the toys from the triangle should be pretty straight forward depending on the method you want to use. I added a toyArray that you can iterate through to remove them.
Checking if a position is within the desired boundaries and rejecting it if it's not is certainly a solution. However, this stops the program from being deterministic, because you never know how many tries it takes before a position within the boundaries is found.
Does that mean the program could run forever? Possibly yes, but this is so unlikely that it's not going to happen. Depending on how much of its bounding box a triangle fills, it will still produce quite a few misses though. Misses that have to be checked, rejected and tried again.
I'm not advising against this strategy because it might be a performance problem (and it might actually be one), but rather because it seems to miss the point: if positions in a triangle should be found, let's just do exactly that. All this trial and error and testing and rejecting is counterintuitive.
You only have one pseudo random number generator built in: Math.random().
That produces an evenly distributed random number between 0 and 1. (let's ignore whether the boundaries are possible values or not)
To create a 2D distribution, it's very easy to simply use two of those.
Now the problem with the even distribution is that it's even. To form a non-rectangular shape, transformations have to be applied.
Consider two edges of the triangle to be two vectors. A random point in the triangle is found by combining those two vectors linearly in a random way.
Obviously, with the untransformed random numbers, that would yield a diamond shaped boundary for the random points. To compensate for the fact that the vectors meet at one point and diverge in the other direction the square root is applied to one random number. The math behind that is not too complicated but ain't trivial either. I choose to omit it here. For more information ask a new question, math.se is probably a good place to do this.
Here's a full fledged example code to be used as a document class, which puts 1000 circles into a triangle boundary:
package
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
public class Main extends Sprite
{
public function Main()
{
var distribution:EvenDistribution2DTriangleBoundary = new EvenDistribution2DTriangleBoundary(new Point(100, 100), new Point(400, 50), new Point(250, 350));
for (var i:int = 0; i < 1000; ++i)
{
// create an object in each iteration of the loop
var circle:Shape = new Shape();
//add some graphics (this is unnecessary if you use a library symbol)
circle.graphics.beginFill(0xff0000, .6);
circle.graphics.drawCircle(0, 0, 3);
circle.graphics.endFill();
// add it to the display list
addChild(circle);
// reposition it with the help of the distribution object
distribution.positionDisplayObject(circle);
}
}
}
}
import flash.display.DisplayObject;
import flash.geom.Point;
internal class EvenDistribution2DTriangleBoundary
{
private var u:Point;
private var v:Point;
private var position:Point;
public function EvenDistribution2DTriangleBoundary(a:Point, b:Point, c:Point)
{
// consider corner "a" as the position of the triangle, this is arbitrary decision, but has to be consistent with the rest of this constructor
position = a;
// create two vectors from the corner that is the position to the other two corners respectively
u = b.subtract(a);
v = c.subtract(a);
}
public function getRandomPosition():Point
{
// random position formula with two random variables: position + (u + (v-u) * random1) * sqrt(random2)
var r1:Number = Math.random();
// the sqrt transforms the probability density function of the even distribution f(x) = 1 into a triangle g(y) = 2y
var r2:Number = Math.sqrt(Math.random());
// applying the above formula to create an evenly distributed random position within the triangle
return position.add(new Point((u.x + (v.x - u.x) * r1) * r2, (u.y + (v.y - u.y) * r1) * r2));
}
// convenience function to position a display object at a random position in the triangle
public function positionDisplayObject(object:DisplayObject):void
{
var position:Point = getRandomPosition();
object.x = position.x;
object.y = position.y;
}
}
Creating the random distribution is a class of its own. For the sake of simple testing, it's an internal class, thus the entire example is a single class that goes into a single file. Of course, in production code, this should be better organised.
Here are 4 results that I got:
it seems I need to transfer all of my frames/timeline code (and there's a lot!) into the external class
That isn't necessary although it is recommended. You should eventually only use class based code, but of course making that transition within a project isn't very practical.
In my example above, there are two classes: Main and EvenDistribution2DTriangleBoundary. You are only interested in the latter one. Main is just there to use the other class, create and display the circles, etc: it's a demo.
To use EvenDistribution2DTriangleBoundary in your project, create a new text file in the same directory as your .fla file named EvenDistribution2DTriangleBoundary.as with the following content:
package
{
import flash.display.DisplayObject;
import flash.geom.Point;
public class EvenDistribution2DTriangleBoundary
{
private var u:Point;
private var v:Point;
private var position:Point;
public function EvenDistribution2DTriangleBoundary(a:Point, b:Point, c:Point)
{
position = a;
u = b.subtract(a);
v = c.subtract(a);
}
public function getRandomPosition():Point
{
var r1:Number = Math.random();
var r2:Number = Math.sqrt(Math.random());
return position.add(new Point((u.x + (v.x - u.x) * r1) * r2, (u.y + (v.y - u.y) * r1) * r2));
}
public function positionDisplayObject(object:DisplayObject):void
{
var position:Point = getRandomPosition();
object.x = position.x;
object.y = position.y;
}
}
}
Now you can use that class like any other class in your project. For example, you can add the code from Main's constructor to your timeline and it should work:
var distribution:EvenDistribution2DTriangleBoundary = new EvenDistribution2DTriangleBoundary(new Point(100, 100), new Point(400, 50), new Point(250, 350));
for (var i:int = 0; i < 1000; ++i)
{
// create an object in each iteration of the loop
var circle:Shape = new Shape();
//add some graphics (this is unnecessary if you use a library symbol)
circle.graphics.beginFill(0xff0000, .6);
circle.graphics.drawCircle(0, 0, 3);
circle.graphics.endFill();
// add it to the display list
addChild(circle);
// reposition it with the help of the distribution object
distribution.positionDisplayObject(circle);
}
You should see a triangle of red circles similar to those I posted in the image of results above. Does that work?

Creating Top Down Shooter in Adobe Flash CS4 using ActionScript 3 but bullets behaving weirdly

I am making a TDS in Flash CS4 using AS3 but there seems to be a problem. It's hard to explain so I'm gonna link the flash file. Click this.
This is the first time uploading a file for sharing so for those who can't or are unable to download the file, this is what happens:
Player has mouse rotation that is, Player looks at where the mouse is. On Mouse down I've put the script for creating bullets. The bullets are being created alright. But when the bullets move that's when the problem arises. Say that at position and rotation X, I shot 5 bullets and they are moving in X direction. Now if I shoot a bullet in Y position and rotation, the bullet that was created there goes in Y direction but so do all the other bullets that were created in the X position and direction. They change their course.
Here is the code for the game.
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Mouse;
import flash.events.TimerEvent;
public class Main extends MovieClip {
var player : Player = new Player();
//Customizable Weapon Settings
var bulletNumber:Number;//number of bullets per shot
var bulletOffset:Number;//bigger number = less acurate
var bulletSpeed:Number;//pixels per frame
var bulletMaxAge:Number;//1000 = 1 second
var reloadSpeed:Number;//1000 = 1 second
var randomNum:Number;
public static var xSpeed:Number;
public static var ySpeed:Number;
var bulletAngle:Number;
var timer:Number=0;
var flag:Boolean;
//other variables (do not edit)
var mouseClicked:Boolean=false;
var radians:Number=Math.PI/180;
public function Main() {
player.x=stage.stageWidth/2;
player.y=stage.stageHeight/2;
stage.addChild(player);
player.gotoAndStop(5);
loadWeapon("Machine Gun");
addEventListener(Event.ENTER_FRAME,on_enter_frame);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
}
public function onMouseDownHandler(event:MouseEvent) {
//trace("Mouse Down");
mouseClicked=true;
flag=true;
}
public function onMouseUpHandler(event:MouseEvent) {
//trace("Mouse Up");
mouseClicked=false;
flag=false;
timer=0;
}
public function loadWeapon(weaponType:String) {
switch (weaponType) {
case "Machine Gun" :
//bulletNumber = 100;
bulletOffset=10;
bulletSpeed=10;
bulletMaxAge=1000;
break;
}
}
function on_enter_frame(e:Event) {
trace("Click: "+ mouseClicked);
fireWeapon();
}
function fireWeapon() {
//check if mouse is clicked
//if true, create bullet
if (mouseClicked) {
createBullet();
player.gotoAndStop(10);
} else {
player.gotoAndStop(1);
}
}
public function createBullet() {
var bullet : Bullet2= new Bullet2();
bullet.x=player.x;
bullet.y=player.y;
if (flag) {
timer++;
if (timer==10) {
trace("lol");
//calculate random bullet offset.
randomNum = Math.random() * (bulletOffset);
//set bullet firing angle
bulletAngle = (player.rotation + randomNum) * radians;
//set bullet speed based on angle
xSpeed=Math.cos(bulletAngle)*bulletSpeed;
ySpeed=Math.sin(bulletAngle)*bulletSpeed;
//trace (bulletAngle);
stage.addChild(bullet);
bullet.addEventListener(Event.ENTER_FRAME, runForest);
//mouseClicked = false;
timer=0;
}
}
function runForest(e:Event) {
bullet.x+=xSpeed;
bullet.y+=ySpeed;
}
}
}
}
Things that I've tried:
1) I put the "runForest()" funtion outside of "createbullet()" function which give me a "1120: Access of undefined property bullet." Error. (Which doesn't make sense since I am giving it a enter frame event listener.)
2) For solving this, I made the bullet variable global and declared it inside the "createbullet()" function like this- "var bullet : Bullet2;" And inside createbullet()- "bullet = new Bullet2();" That gives me a completely different output.
3) I put the "runForest()" function in its own class file. But the same thing is happening.
I was referring to a Tutorial that used AS2. This is the link.
Help me solve this please.
Thanks!
Review this code:
//set bullet speed based on angle
xSpeed=Math.cos(bulletAngle)*bulletSpeed;
ySpeed=Math.sin(bulletAngle)*bulletSpeed;
then take a look at how these variables for speed are created:
public static var xSpeed:Number;
public static var ySpeed:Number;
You have 1 variable for the x direction of the speed. If there is only one variable, there can only be 1 value for speed.
that's why all your bullets are moving in the same direction, because they all share that one single value for speed, which causes them to go into the same direction.
Your Main class is doing everything at the moment and you should really refactor some of that code into several other classes.
Even your own understanding of the code you are writing is not reflected by the code, your comment says:
//set bullet speed based on angle
Now why is that bullet speed a variable of Main? Object oriented programming is made exactly for that. You can literally turn your plain English description of the desired behaviour into code.
When you say that you "want to have Bullets", then create a Bullet class.
When you say "each Bullet object should have its own speed", then add a property to that class that is the speed.
You will encounter the same problem with your weapons and the same solution applies.

Timer stops working properly after a few seconds

I have a tween playing every few seconds, and it works fine in the beginning, but then it starts to get jittery and resets before it even gets halfway through the tween.
Any idea why? the timer also seems to have a longer wait the first time i run the animation
import flash.events.Event;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
addEventListener(Event.ENTER_FRAME, move);
var signalTimer:Timer = new Timer(3000, 0);
function move(e:Event){
sender.x = mouseX;
sender.y = mouseY;
signalTimer.addEventListener(TimerEvent.TIMER, sendSignal);
signalTimer.start();
}
function sendSignal(e:TimerEvent){
signalTimer.stop();
var sigTween1X:Tween = new Tween(signal1, "x", None.easeOut, sender.x, mic1.x, 10, false);
var sigTween1Y:Tween = new Tween(signal1, "y", None.easeIn, sender.y, mic1.y, 15, false);
var sigTween3X:Tween = new Tween(signal3, "x", Strong.easeIn, sender.x, mic3.x, 7, true);
var sigTween3Y:Tween = new Tween(signal3, "y", Strong.easeOut, sender.y, mic3.y, 7, true);
}
This is a heavy segment of code; combining frame-based, timer, and tween timings.
Currently each frame calls move() which adds an event listener to your signalTimer without removing the previously added event listener:
signalTimer.removeEventListener(TimerEvent.TIMER, sendSignal);
However, adding and removing an event listener per frame is not optimal.
If you really want your timer to fire every 3-seconds, instantiate and add an event listener upon instantiation (not within the move() function):
var signalTimer:Timer = new Timer(3000, 0);
signalTimer.addEventListener(TimerEvent.TIMER, sendSignal);
signalTimer.start();
Then don't stop the timer in sendSignal().
Addressing the tweens, you could implement frame-based animation such as:
signal1.x -= (signal1.x - mic1.x) * 0.9;
signal1.y -= (signal1.y - mic1.y) * 0.9;
Therefore, implementing a delta based function to track x,y coordinates.

Movieclips clashing with bitmap mask

I am trying to reveal this movie clip image which is originally a bitmap but needs to be used as a bitmap for this purpose. for some reason it's not working ...
It's not throwing any errors... I need this image to be masked as the user presses on it... and later be compared with another bitmap to carry out a function. but for some reason as I mentioned before it's not working out. can somebody please help me?? this is the code for it...
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.display.BitmapData;
var mouseclick:Number=0;
var maskedbg_mc:maskedbg = new maskedbg ();
var masking:Sprite = new Sprite()
addChild (maskedbg_mc);
maskedbg_mc.x = 18;
maskedbg_mc.y = 343;
var bitmapDataCopy:BitmapData = new BitmapData(742,165,true,0x00FFFFFF);
var b:Bitmap = new Bitmap(bitmapDataCopy);
bitmapDataCopy.draw(maskedbg_mc);
b.mask = masking;
var Testing:BitmapData = new BitmapData(maskedbg_mc.width, maskedbg_mc.height, true, 0x00000000);
addChild(masking);
stage.addEventListener(MouseEvent.MOUSE_DOWN, Pressing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, Moving);
stage.addEventListener(MouseEvent.MOUSE_UP, Lifting);
function Pressing(event:MouseEvent):void {
mouseclick = 1;
}
function Moving(event:MouseEvent):void {
if (mouseclick == 1) {
masking.graphics.beginFill(0x000000);
masking.graphics.drawEllipse(mouseX, mouseY, 70, 60);
masking.graphics.endFill();
}
}
function Lifting(event:MouseEvent):void {
mouseclick = 0;
}
if ( bitmapDataCopy.compare(Testing) ==0 )
{
trace ("Awesomness")
}
Overlooking your code, I notice you are not adding "b" (the masked DisplayObject) to the display list, while you are adding "maskedbg_mc" which actually isn't being masked in your code. Do you have a reason for having these 2 display objects?
I would recommend you following actionscript coding conventions:
http://sourceforge.net/adobe/flexsdk/wiki/Coding%20Conventions/
Your code looks quite confusing when you have both variables and functions with initial letter in uppercase, they look like classes.

Endless repeating scrolling background

I got a problem with AS3 and AIR. I'm working on a side-scrolling game for smartphones with a plane and I use different backgrounds as layers.
Before all other: I use GPU and only bitmaps, quality is set to low. So Performance settings are all set for smartphone use.
I putted them into a rectangle using the drawing API and move the background with a matrix:
protected var scrollingBitmap:BitmapData;
protected var canvas:Graphics;
protected var matrix:Matrix;
public function move(dx:Number, dy:Number):void {
matrix.translate(dx, dy);
if(dx != 0) matrix.tx %= scrollingBitmap.width;
if(dy != 0) matrix.ty %= scrollingBitmap.height;
drawCanvas();
}
protected function drawCanvas():void {
canvas.clear();
canvas.beginBitmapFill(scrollingBitmap, matrix, true, true);
canvas.drawRect(0, -scrollingBitmap.height, 1404, scrollingBitmap.height);
}
UPDATE2 (
Take a look at this: http://plasticsturgeon.com/2010/06/infinite-scrolling-bitmap-backgrounds-in-as3/
I used this to create my backgrounds.
With this I can simulate that my plane is flying to the right without moving the whole background and I can use a small single graphic which repeats every time (for the foreground layer).
For the background layer I use this method, too, but with a much larger graphic and I move it only with less the speed of my plane to simulate a far background.
My move-method is on an enterframe event. So I can update the background every frame with the "movement" of my plane.
)
The plane can exceed the height of the bitmaps. Everytime the bitmap comes back into the window/screen a real long lag occurs. And when the plane flies very fast, the game start to lag, too.
My first approach was to use .PNG files (but they are very big: 1-3MB size).
My next approach was to use .GIF files (much less size).
With both it's the same. So it can't be that.
I read about draw() and copyPixels() but I don't know, how I can use those to repeat the image.
UPDATE1:
protected var scrollingBitmap:BitmapData;
protected var canvas:Bitmap;
protected function init(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
canvas = new Bitmap(new BitmapData(1404, scrollingBitmap.height, true), "auto", true);
this.addChild(canvas);
drawCanvas();
}
public function move(dx:Number, dy:Number):void {
if(dx != 0) dx %= scrollingBitmap.width;
if(dy != 0) dy %= scrollingBitmap.height;
drawCanvas(dx, dy);
}
protected function drawCanvas(xPos:Number = 0, yPos:Number = 0):void {
canvas.bitmapData.copyPixels(scrollingBitmap, new Rectangle(0, 0, 1404, scrollingBitmap.height), new Point(xPos, yPos), scrollingBitmap);
}
I think you'd be better off with a Bitmap instead of using the graphics object with fill. copyPixels is very fast. So what you'd do is simply copyPixels over the top of whatever was there before, presuming everything is opaque. If everything is not opaque, you'll need to use your source bitmap as its own alpha data so previously drawn pixels don't show through.
Let's reframe your canvas so it is a Bitmap and not a MC. your new code will look like:
protected function drawCanvas():void {
canvas.bitmapData.copyPixels(scrollingBitmap, new Rectangle(0, 0, scrollingBitmap.width, scrollingBitmap.height), new Point(0,0), scrollingBitmap);
}
Oh, and look at that! Not only is this code faster, it's only one line of code!
EDIT: Added working code
package {
import flash.display.MovieClip;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.geom.Rectangle;
import flash.geom.Point;
public class EndlessBG extends MovieClip{
//this one stays stationary, we're getting the pixels for the right side of the pic from here
private var _source:BitmapData;
//this is the one moving to the left (the pixels for the right side are not visible except for once a cycle);
private var _movingPixels:BitmapData;
private var _canvas:Bitmap;
private var _xOffset:int = 0;
private var _rect:Rectangle = new Rectangle();;
private var _point:Point = new Point();
public function EndlessBG() {
super();
_source = new BathroomStillLife();
_canvas = new Bitmap(new BitmapData(_source.width, _source.height));
_canvas.bitmapData.draw(_source);
_canvas.x = stage.stageWidth/2 - _canvas.width/2;
_canvas.y = 5;
addChild(_canvas);
addEventListener(Event.ENTER_FRAME, gameLoop);
setGeometryDefaults();
_movingPixels = new BitmapData(_source.width, _source.height);
_movingPixels.copyPixels(_source, _rect, _point);
//turn this on to watch red pixels be drawn where the source pixels are coming in
//_source = new BitmapData(_source.width, _source.height, false, 0xFF0000);
}
private function gameLoop(e:Event):void {
_xOffset--;//where the background is moving to
if (_xOffset < -_source.width) {
_xOffset = 0;
//this doesn't seem to work correctly:
//_movingPixels.scroll(_source.width, 0);
_movingPixels = new BitmapData(_source.width, _source.height);
_movingPixels.copyPixels(_source, _rect, _point);
}
trace(_xOffset);
setGeometryDefaults();
_movingPixels.scroll(-1, 0);
//draw the moved part of the canvas
_canvas.bitmapData.copyPixels(_movingPixels, _rect, _point);
//If we stop here, we get a smear to the right
//so, get the remaining pixels directly from the source
//1) reset our rect and point to be to the right side
_rect.x = 0;
_rect.width = -_xOffset;
_point.x = _source.width + _xOffset;
//2) copy from the source
_canvas.bitmapData.copyPixels(_source, _rect, _point);
}
private function setGeometryDefaults():void {
_rect.x=0;
_rect.y=0;
_rect.width = _source.width;
_rect.height = _source.height;
_point.x = 0;
_point.y = 0;
}
}
}
Not ideal, and not polished enough yet for a blog post, but should get you started.
Edit:
Eventually I did write that blog post.
http://www.greensock.com/blitmask
This might help although not free