AS3: Why is this fluid simulation running slower and slower? - actionscript-3

I'v got 2 classes. Simulating fluid. Both classes are pretty straight forward and short, but after 2 seconds of running, the simulation gets really slow, looks like a memory leak. But i can't see any leaks in this code.
Please let me know if you can figure out, why this is happening?
FluidLayer.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.filters.BlurFilter;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.geom.ColorTransform;
import flash.display.IBitmapDrawable;
import flash.events.Event;
import flash.display.MovieClip;
public class FluidLayer extends MovieClip {
private var canvas:Sprite;
private var b:Bitmap;
private var blur:BlurFilter = new BlurFilter(20,20,3);
private var bmd1:BitmapData;
public function FluidLayer() {
canvas = new Sprite();
for(var i:int = 0;i < 600;i++){
var p:Particle = new Particle();
canvas.addChild(p);
p.x = stage.stageWidth * Math.random();
p.y = stage.stageHeight* Math.random();
p.initi(stage);
}
canvas.filters = new Array(blur);
addEventListener(Event.ENTER_FRAME, render);
}
private function render(e:Event):void{
remove();
b = new Bitmap(makeFluid(canvas),"auto", true);
b.alpha = 0.7;
addChild(b);
}
private function makeFluid(o:Sprite):BitmapData{
bmd1 = new BitmapData(stage.stageWidth, stage.stageHeight, true);
bmd1.draw(o,null,null,null,null,true);
bmd1.threshold(bmd1, bmd1.rect, new Point(0,0), ">", 0XFF2b2b2b, 0x55FFFF, 0xFFFFFF, false);
return bmd1;
}
private function remove():void{
if(numChildren > 1)
removeChildAt(1);
if(bmd1){
bmd1.dispose();
bmd1 = null;
}
}
}}
Particle.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Particle extends MovieClip {
private var speedX:int;
private var speedY:int;
private var _s:Stage;
public function Particle() {
this.graphics.beginFill(0x00CCFF);
this.graphics.drawCircle(0,0,Math.random() * 30);
speedX = Math.random() * 10 - 5;
speedY = Math.random() * 10 - 5;
this.addEventListener(Event.ADDED_TO_STAGE, initi);
}
public function initi(s:Stage):void{
this._s = s;
addEventListener(Event.ENTER_FRAME, render);
}
private function render(e:Event):void{
this.x += Math.random()*speedX;
this.y += Math.random()*speedY;
if(this.x > _s.stageWidth || this.y > _s.stageHeight){
//this.x = Math.random()*_s.stageWidth;
//this.y = Math.random()*_s.stageHeight;
removeEventListener(Event.ENTER_FRAME, render);
this.parent.removeChild(this);
}
}
}}

You must call bmd1.dispose(); before reinstantiating it or it will not release the bitmap from memory.
Edit:
After looking through your code very carefully, optimizing it, and cleaning up some things, I have come to the conclusion that your simulation is no longer running slower and slower.
The problem was that the way you would calculate the particle's x and y speed. Essentially it would diminish in speed until stopping all together. On top of the massive high quality blur you have placed and the lack of freeing bitmaps, your movie would appear and actually slow to a crawl.
Here is your code I have modified. I benchmarked it and it didn't peak above 10% cpu or 40k memory after 15 minutes.
Particle.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Particle extends MovieClip {
private var speedX:int;
private var speedY:int;
private var deleted:Boolean = false;
public function Particle() {
this.graphics.beginFill(0x00CCFF);
this.graphics.drawCircle(0,0,Math.random() * 30);
//The max prevents particle speed from rounding to zero.
speedX = Math.ceil(Math.random() * 10 - 5);
speedY = Math.ceil(Math.random() * 10 - 5);
}
public function render():void{
//It originally appeared to be slowing down. In-fact, it was.
x += Math.random() * speedX;
y += Math.random() * speedY;
deleted = (x > FluidLayer.w || y > FluidLayer.h);
//Comment this below if you want particles to be removed once they go out of bounds.
if(deleted) {
x = Math.random() * FluidLayer.w;
y = Math.random() * FluidLayer.h;
deleted = false;
}
}
public function isDeleted():Boolean {
return deleted;
}
}
}
FluidLayer.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.filters.BlurFilter;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.geom.ColorTransform;
import flash.display.IBitmapDrawable;
import flash.events.Event;
import flash.display.MovieClip;
public class FluidLayer extends MovieClip {
private var canvas:Sprite;
private var bitmap:Bitmap;
private var bitmapData:BitmapData;
private var particleArray:Array = new Array();
public static const w:uint = 550;
public static const h:uint = 400;
public function FluidLayer() {
addEventListener(Event.ADDED_TO_STAGE, initialize);
}
//By only one event handler to render, we prevent the overhead of 599 bubbling events.
private function render(e:Event):void {
for each(var p:Particle in particleArray) {
p.render();
//uncomment below if you want particles to become removed when they navigate out of bounds.
//if(p.isDeleted()) {
//canvas.removeChild(p);
//particleArray.splice(particleArray.indexOf(p),1);
//}
}
bitmapData.fillRect(bitmapData.rect, 0); //clear the bitmapdata
bitmapData.draw(canvas,null,null,null,null,true);
bitmapData.threshold(bitmapData, bitmapData.rect, new Point(0,0), ">", 0XFF2b2b2b, 0x55FFFF, 0xFFFFFF, false);
}
//We call initialize once the fluid layer has been added to stage
//or else stage values will be null.
private function initialize(e:Event):void {
canvas = new Sprite();
//You DEFINITELY want to lower the blur amount here.
//This is what is ultimately slowing your SWF down to a crawl.
//canvas.filters = new Array(new BlurFilter(20,20,1));
for(var i:uint = 0; i < 600; i++) {
var p:Particle = new Particle();
p.x = Math.random() * w;
p.y = Math.random() * h;
canvas.addChild(p);
particleArray.push(p);
}
//The bitmap and bitmapData only need to be initialized once
bitmapData = new BitmapData(w, h, true);
bitmap = new Bitmap(bitmapData, "auto", true);
bitmap.alpha = 0.7;
addChild(bitmap);
addEventListener(Event.ENTER_FRAME, render);
}
}
}

The original slowdown appears to be the blur filter on the canvas. (Comment the filter out to see proof)
The automatic creation of bitmaps by flash (CacheAsBitmap & Bitmap Filter buffers) to render the filter is likely causing the memory leak and this could be due the constantly changing dimension of canvas, due to the particles movement.
Try adding this line after creating canvas for a quick fix:
canvas.scrollRect = new Rectangle(0,0,stage.stageWidth,stage.stageHeight);
By limiting the size of the canvas with the scrollRect we are stopping this reallocation.
However the fluid no longer goes to the edges of the stage. This could be worked around in the draw and bitmap allocation routines, increasing dimensions and offsetting, i'll let you have a go at that but its connected partially to the blur filter amount.
I'd suggest adapting these idea with the very good ideas in Andreas' code.

So i put together a solution for my question with the help of Andreas and adamh.
Andreas - showed me that i forgot to dispose the bitmapdata (really nice spot!)
Adamh - told me to define scrollrect on the canvas (Upped the performance a lot!)
But what did it in the end and made the performance fluid, was a simple mistake from my side. I noticed in the particle.as > render(), that i was only checking if the particle was out of bounds on 2 sides (facepalm), stupid mistake. When i changed the render function to check the remaining 2 sides, it fixed the performance issue.
Sorry for the stupid question :) and thanks again to Andreas and adamh
the final classes:
FluidLayer.as
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.BitmapData;
import flash.filters.BlurFilter;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.geom.ColorTransform;
import flash.display.IBitmapDrawable;
import flash.events.Event;
import flash.display.MovieClip;
import flash.geom.Rectangle;
public class FluidLayer extends MovieClip {
private var canvas:Sprite;
private var b:Bitmap;
private var blur:BlurFilter = new BlurFilter(20,20,3);
private var bmd1:BitmapData;
public function FluidLayer() {
canvas = new Sprite();
canvas.scrollRect = new Rectangle(0,0,1010,550);
for(var i:int = 0;i < 600;i++){
var p:Particle = new Particle();
canvas.addChild(p);
p.x = stage.stageWidth * Math.random();
p.y = stage.stageHeight* Math.random();
p.initi(stage);
}
canvas.filters = new Array(blur);
addEventListener(Event.ENTER_FRAME, render);
}
private function render(e:Event):void{
remove();
b = new Bitmap(makeFluid(canvas),"auto", true);
b.alpha = 0.7;
addChild(b);
}
private function makeFluid(o:Sprite):BitmapData{
bmd1 = new BitmapData(stage.stageWidth, stage.stageHeight, true);
bmd1.draw(o,null,null,null,null,true);
bmd1.threshold(bmd1, bmd1.rect, new Point(0,0), ">", 0XFF2b2b2b, 0x55FFFF, 0xFFFFFF, false);
return bmd1;
}
private function remove():void{
if(numChildren > 1)
removeChildAt(1);
if(bmd1){
bmd1.dispose();
bmd1 = null;
}
}}}
Particle.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
public class Particle extends MovieClip {
private var speedX:int;
private var speedY:int;
private var _s:Stage;
public function Particle() {
this.graphics.beginFill(0x00CCFF);
this.graphics.drawCircle(0,0,Math.random() * 30);
speedX = Math.random() * 10 - 5;
speedY = Math.random() * 10 - 5;
this.addEventListener(Event.ADDED_TO_STAGE, initi);
}
public function initi(s:Stage):void{
this._s = s;
addEventListener(Event.ENTER_FRAME, render);
}
private function render(e:Event):void{
this.x += Math.random()*speedX;
this.y += Math.random()*speedY;
if(this.x > _s.stageWidth || this.y > _s.stageHeight || this.x < 0 && this.y < 0){
this.x = Math.random()*_s.stageWidth;
this.y = Math.random()*_s.stageHeight;
//removeEventListener(Event.ENTER_FRAME, render);
//this.parent.removeChild(this);
}
}
}}

Related

hitTest not working

I don't understand. HitTest is pretty basic but it won't work. I want my movieclip Faller to hitTest Touch1 but I get error 1061. I tought I had it done when I did fallerThingsLeft to hitTest Touch1 to tell me "HIT" on the score_txt, but it tells me Hit like 3 sec
before it really hits. I don't get it. can't someone tell me what im doing wrong
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
var objectSpawner: Timer;
var fallers: Array;
function initGame(): void {
fallers = [];
objectSpawner = new Timer(1000);
objectSpawner.addEventListener(TimerEvent.TIMER, createEnemy);
objectSpawner.start();
addEventListener(Event.ENTER_FRAME, dropEnemies);
}
function createEnemy(e: TimerEvent): void {
var enemy: Faller = new Faller();
enemy.y = -stage.stageHeight;
enemy.x = Math.random() * 380;
MovieClip(enemy).cacheAsBitmap = true;
addChild(enemy);
fallers.push(enemy);
drawConnectors();
}
function dropEnemies(e: Event): void {
trace(fallers.length);
for each(var mc: Faller in fallers) {
mc.y += 10;
if (mc.y > stage.stageHeight * 2)
fallers.splice(fallers.indexOf(removeChild(mc)), 1);
drawConnectors();
}
}
function drawConnectors(): void {
if (fallers.length == 0) return;
var g: Graphics = this.graphics;
g.clear();
g.lineStyle(10,0xFFFFFF);
var mc: Faller = fallers[0];
g.moveTo(mc.x, mc.y);
for each(mc in fallers) g.lineTo(mc.x, mc.y);
}
init()
function init():void
{
var fallingThingsLeft:FallingThings = new FallingThings
(stage.stageWidth / 2, stage.stageHeight);
var fallingThingsRight:FallingThings = new FallingThings
(stage.stageWidth / 2, stage.stageHeight);
addChild(fallingThingsLeft);
addChild(fallingThingsRight);
fallingThingsRight.x = stage.stageWidth / 2;
}
import flash.events.Event;
this.addEventListener( Event.ENTER_FRAME, handleCollision)
function handleCollision( e:Event ):void
{
if(fallingThingsLeft.hitTestObject(Touch1))
{
output_txt.text = "HIT"
}
else
{
output_txt.text = "MISS"
}
}
Without seeing the objects, I can't be certain; however a common issue when getting started with hitTestObject is understanding the hit test is performed on the bounding box. See the image below. This will register a 'hit' with hitTestObject because the bounding boxes pass the hit test.

as3 hitTestPoint detecting alpha

I am trying to make maze where the user draws with mouse and if they hit the wall it erases the line they just drew. I have a png file with alpha that creates the walls of the maze.
I need the user to draw on the alpha but when they hit a non alpha it will trigger an action and erase the line.
Here is the line I am having issues with:
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
Here is the full code:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theBall:Ball = new Ball();
//alreadyDrawn = new Shape();
public function MazeClass()
{
if (stage)
{
myshape = new Shape();
myshape.graphics.lineStyle(12,0x000000);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
addChild(theBall);
}
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
drawing = true;
}
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
{
trace("Hit A WALL!");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xFFFFFF);
myshape.graphics.moveTo(mouseX,mouseY);
}
}
}
public function stopDrawing(event:MouseEvent)
{
drawing = false;
}
}
}
Another option is to test the colour of the map bitmapdata pixel that corresponds to the "player's position" (the end of the drawn line, in this case):
var testPixel:uint = _myBitmapData.getPixel(xPosition, yPosition);
Or you can use .getPixel32 which includes alpha in the returned uint.
I FOUND A WORKING SOLUTION:
I found a working solution thanks to fsbmain. Thank you. I am posting my full code in hopes that this can help someone else.
In the end I had to use another movieClip rather than the mouse, but this worked for me. Now instead of drawing anywhere in the maze they have to drag a little character named Beau thru the maze. This works better for me.
It would be nice to know how to also detect if the mouse or the actual line I am drawing hit the wall as well. Maybe someone can make a suggestion. Nevertheless, thanks for helping me get this far.
The short and essential code to make my movieClip detect the alpha can be found here. It really is very short compared to other complicated options I found. Here is the link: http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.desktop.NativeApplication;
import flash.system.Capabilities;
import flash.display.*;
import flash.geom.*;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Matrix;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theMap:*;
public var swiper:Swiper = new Swiper();
public var Beau:littleBeau = new littleBeau();
//alreadyDrawn = new Shape();
public var currentGalleryItem:Number = 1;
public var totalGalleryItems:Number = 4;
public var redClipBmpData:BitmapData;
public var blueClipBmpData:BitmapData;
public var redRect:Rectangle;
public var blueRect:Rectangle;
public function MazeClass()
{
if (stage)
{
theMap = new MapOne();
myshape = new Shape();
myshape.graphics.lineStyle(33,0x0aa6df);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_OptionsMenuHandler);
Multitouch.inputMode = MultitouchInputMode.GESTURE;
addChild(theMap);
//theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(swiper);
swiper.y = stage.stageHeight - swiper.height;
swiper.addEventListener(TransformGestureEvent.GESTURE_SWIPE, fl_SwipeToGoToNextPreviousFrame);
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
Beau.addEventListener(MouseEvent.MOUSE_DOWN, BeauStartDrag);
Beau.addEventListener(MouseEvent.MOUSE_UP, BeauStopDrag);
redRect = theMap.getBounds(this);
redClipBmpData = new BitmapData(redRect.width,redRect.height,true,0);
redClipBmpData.draw(theMap);
blueRect = Beau.getBounds(this);
blueClipBmpData = new BitmapData(blueRect.width,blueRect.height,true,0);
blueClipBmpData.draw(Beau);
//blueClipBmpData.x = theMap.theStart.x;
//blueClipBmpData.y = theMap.theStart.y - swiper.height;
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
}
}
public function enterFrame(e:Event):void
{
//Beau.x = mouseX;
//Beau.y = mouseY;
if (redClipBmpData.hitTest(new Point(theMap.x, theMap.y),
255,
blueClipBmpData,
new Point(Beau.x, Beau.y),
255
))
{
trace("hit");
clearAll();
//redClip.filters = [new GlowFilter()];
}
else
{
trace("No Hit");
}
}
public function BeauStartDrag(event:MouseEvent):void
{
Beau.startDrag();
drawing = true;
}
public function BeauStopDrag(event:MouseEvent):void
{
drawing = false;
Beau.stopDrag();
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
}
//drawing = true;
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
}
}
public function stopDrawing(event:MouseEvent)
{
//drawing = false;
}
public function fl_OptionsMenuHandler(event:KeyboardEvent):void
{
if ((event.keyCode == 95) || (event.keyCode == Keyboard.MENU))
{
NativeApplication.nativeApplication.exit(0);
}
}
public function clearAll()
{
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0x0aa6df);
myshape.graphics.moveTo(mouseX,mouseY);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
drawing = false;
Beau.stopDrag();
}
public function fl_SwipeToGoToNextPreviousFrame(event:TransformGestureEvent):void
{
if (event.offsetX == 1)
{
if (currentGalleryItem > 1)
{
currentGalleryItem--;
trace("swipe Right");
clearAll();
removeChild(theMap);
theMap = new MapOne();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
else if (event.offsetX == -1)
{
if (currentGalleryItem < totalGalleryItems)
{
currentGalleryItem++;
trace("swipe Left");
clearAll();
removeChild(theMap);
theMap = new MapTwo();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
}
}
}

Object class rotating wrongly when it's called in movieclip class (My Arcade Game)

i have Cannon's class and it can rotate towards player !!
package com.musuh {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.sampler.NewObjectSample;
import com.ply.Heli;
public class Cannon extends MovieClip {
public var enTarget:Heli;
public function Cannon(enTarget:Heli) {
this.enTarget = enTarget;
addEventListener(Event.ENTER_FRAME , update);
}
public function fire (m:MouseEvent){
trace("fire");
}
function update (e:Event) {
if (parent != null) {
var dx = enTarget.x - x ;
var dy = enTarget.y - y ;
var angle = Math.atan2(dy,dx)/Math.PI*180-90;
rotation = angle;
}
}
}
}
when i called it to main class , it works fine (it can rotating towards player ) !!! , but when i called it inside Boss class (because in my game this boss can have at least 3 cannon ),it wasn't error but rotate wrongly towards player .. Why is it like that ?
it's the Boss Class
package com.musuh {
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.getTimer;
import com.peluru.bossBullet;
import com.ply.Heli;
import com.musuh.Cannon;
public class Boss extends MovieClip {
private var speedX:int = 6;
private var dx:Number; // speed and direction
public var bossHP:Number=20;
private var gun:Cannon;
public var hits:Array;
public var target:Heli;
public function Boss(target:Heli) {
this.target = target;
bossBullets = new Array();
hits = new Array(hit1,hit2,hit3,hit4,hit5,hit6);
addEventListener(Event.ADDED_TO_STAGE , onAddedToStage);
addEventListener(Event.ENTER_FRAME, movePlane)
addEventListener(Event.ENTER_FRAME, update)
}
private function onAddedToStage(event:Event):void
{
gun = new Cannon(target);
gun.x = 0;
gun.y = 200;
// add cannon to the MC Pitboss
addChild(gun);
}
public function movePlane(e:Event){
// move plane
this.x +=speedX;
{
speedX *= -1;
}
if (this.x <= 20)
{
speedX *= -1;
}
}
}
}
and it's the SCREEN SHOOT
http://img268.imageshack.us/img268/9250/1p0a.jpg
can you post the code where you actually add the Boss object? it looks like your
Boss.scaleX = -1
that'd explain the flipped x axis
But without seeing the code where you add your boss to main, I can't be sure.

A loop in enterframe?

I'm animating a bunch of words in AS3. Because I'm going to be using this on a mobile device, I want to use bitmaps rather than Sprites. So I've created WordObjects, which have a .bitmap property that I can access.
I have the following code, which fires on the click event and loops through an array inside an enterframe event. This is probably a bad idea, but I'm not sure how to do it better. (What is surprising is that it runs just fine in Flashbuilder, but slows to a crawl in Flash CS5.)
Is there some better way to do this? I just want an efficient way to animate the array of bitmaps.
private function clickhandler (e:MouseEvent){
this.addEventListener(Event.ENTER_FRAME, blowemup);
}
private function blowemup(e:Event){
var newPosition:Number;
for(var i:int=0; i<arrWordObjects.length; i++)
{
newPosition = updatePosition(arrWordObjects[i].bitmap);
arrWordObjects[i].bitmap.x += newPosition;
arrWordObjects[i].bitmap.y += getRandomNumber();
}
}
Something that will make a huge difference is using for each(Object in Array) rather than the standard for loop.
private function blowemup(e:Event):void
{
var newPosition:Number;
var i:ArrWordsObjectClass; // <-- don't know what the class for this is, just replace
for each(i in arrWordObjects)
{
newPosition = updatePosition(i.bitmap);
i.bitmap.x += newPosition;
i.bitmap.y += getRandomNumber();
}
}
A for each loop is typed, meaning a lot of time is saved where normally it'd be trying to work out what arrWordObjects[i] is every iteration.
Also, side note: using one ENTER_FRAME driven function and looping through everything in your application that you want to handle each frame is much more efficient than applying hundreds of listeners for objects.
I normally create a handler class that contains the ENTER_FRAME and an array storing my objects, like so:
package
{
import flash.events.Event;
import flash.display.Sprite;
public class Handler extends Sprite
{
// vars
public var elements:Array = [];
/**
* Constructor
*/
public function Handler()
{
addEventListener(Event.ENTER_FRAME, _handle);
}
/**
* Called on each dispatch of Event.ENTER_FRAME
*/
private function _handle(e:Event):void
{
var i:Element;
for each(i in elements)
{
i.step();
}
}
}
}
Then I create a base class for all the objects that I want to handle, containing the step() function called above.
package
{
import flash.display.DisplayObject;
public class Element extends Object
{
// vars
public var skin:DisplayObject;
/**
* Called on each dispatch of Event.ENTER_FRAME at Handler
*/
public function step():void
{
// override me
}
}
}
Now just extend Element with your objects:
package
{
import flash.display.Sprite;
public class MyThing extends Element
{
/**
* Constructor
*/
public function MyThing()
{
skin = new Sprite();
skin.graphics.beginFill(0);
skin.graphics.drawCircle(0,0,40);
skin.graphics.endFill();
}
/**
* Override step
*/
override public function step():void
{
skin.x += 4;
}
}
}
And get it all going!:
var handler:Handler = new Handler();
var m:MyThing;
var i:uint = 0;
for(i; i<10; i++)
{
m = new MyThing();
m.y = Math.random()*stage.stageHeight;
handler.elements.push(m);
addChild(m.skin);
}
How many bitmaps do you plan to have on the stage at a time?
I have had 40 900x16px bitmaps animating on the stage at full speed running on my iphone using air 2.6.
I used a foreach loop in an enterframe event which i added on mouseclick and removed once the animation was finished.
Remember to compile it for the mobile with gpu rendering enabled. (gpu in your app.xml if you are using air 2.6)
This is worth a read too, it explains a lot about performance for mobile devices
http://help.adobe.com/en_US/as3/mobile/WS901d38e593cd1bac-3d719af412b2b394529-8000.html
Here is a basic example of what I had...
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
[SWF(frameRate="30", backgroundColor="#FF00FF")]
public class Test extends Sprite
{
private var fields:Vector.<Bitmap> = new Vector.<Bitmap>();
public function Test()
{
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
for(var i:int = 0; i< 37; i++){
var bd:BitmapData = new BitmapData(960, 16, true, 0x000000);
bd.fillRect(new Rectangle(0, 0, 900, 16), Math.round( Math.random()*0xFFFFFFFF ));
var b:Bitmap = new Bitmap(bd);
b.x = 0;
b.y = i*16;
stage.addChild(b);
fields.push(b);
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
private var inertia:Boolean = false;
private var yCurrent:Number;
private var ySpeed:Number;
private var startY:Number;
private var cy:Number = 0;
private function onEnterFrame(e:Event):void{
if(!inertia){
ySpeed = (startY - yCurrent) ; // / 16;
startY = yCurrent
} else {
ySpeed *= 0.8;
if(ySpeed < 0.01 && ySpeed > -0.01){
inertia = false;
stage.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
cy += ySpeed;
if(cy > 640)
cy -= 640;
var ty:Number = cy;
for each(var tf:Bitmap in fields){
tf.y = ty;
ty += 16;
if(ty > 640)
ty -= 640;
}
}
private function onMouseDown(e:MouseEvent):void{
inertia = false;
startY = e.stageY;
yCurrent = e.stageY;
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
private function onMouseMove(e:MouseEvent):void{
yCurrent = e.stageY;
}
private function onMouseUp(e:Event):void{
inertia = true;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
}
}
I would suggest looking at writing a custom effect on Adobe's website over registering for ENTER_FRAME event. What you've put up there means this code will forever run as long as the program is running. If you wanted to stop the effect or run for 10 frames and stop then you'll have to write more code. It gets even more complex if you want to apply this to several instances. You're going to have to resolve problems that custom effects framework solves.
I'd read how to write custom effects here:
http://livedocs.adobe.com/flex/3/html/help.html?content=createeffects_1.html

Need some help completing a bumptop-ish selection tool

I'm in the midst of creating a Bumptop styled selection tool. Right now I got as far as creating the tool itself (which actually works pretty good) and spreading some random square items on the stage. This is the class that creates the selection tool :
package com.reyco1.medusa.selectiontool
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
public class SelectionBase extends Sprite
{
private var points:Array = [];
public function SelectionBase()
{
super();
addEventListener(Event.ADDED_TO_STAGE, initialize);
}
private function initialize(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, initialize);
points.push(new Point(mouseX, mouseY)); stage.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
}
private function handleMouseMove(e:MouseEvent):void
{
graphics.clear();
graphics.beginFill(0x33CCFF, .5);
graphics.drawCircle(0, 0, 20);
graphics.endFill();
graphics.moveTo(0, 0);
graphics.lineStyle(1.5, 0x33CCFF, .5);
graphics.lineTo(mouseX, mouseY);
points.push(new Point(mouseX, mouseY));
graphics.beginFill(0x33CCFF, .1);
graphics.moveTo(points[0].x, points[0].y);
for (var i:uint = 1; i < points.length; i++)
{
graphics.lineTo(points[i].x, points[i].y);
}
graphics.lineTo(points[0].x, points[0].y);
graphics.endFill();
dispatchEvent(new Event("UPDATE"));
}
public function clear():void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
graphics.clear();
}
}
}
And this is the document class that implements it :
package
{
import com.reyco1.medusa.selectiontool.SelectionBase;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
[SWF(width = '1024', height = '768', backgroundColor = '0x000000')]
public class SelectionToolPrototype extends Sprite
{
private var selectionTool:SelectionBase;
public function SelectionToolPrototype()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.MEDIUM;
stage.addEventListener(MouseEvent.MOUSE_DOWN, handleDown);
stage.addEventListener(MouseEvent.MOUSE_UP, handleUp);
placeShapesRandomly();
}
private function placeShapesRandomly():void
{
for(var a:Number = 0; a<25; a++)
{
var s:Sprite = new Sprite();
s.graphics.beginFill(Math.random() * 0xCCCCCC);
s.graphics.drawRect(0, 0, 50, 50);
s.graphics.endFill();
s.x = Math.floor(Math.random() * 900 - 40) + 40;
s.y = Math.floor(Math.random() * 700 - 40) + 40;
s.rotation = Math.floor(Math.random() * 360 - 40) + 40;
s.buttonMode = true;
addChild(s);
}
}
private function handleUp(e:MouseEvent):void
{
selectionTool.removeEventListener("UPDATE", handleToolUpdate);
removeChild(selectionTool);
selectionTool = null;
}
private function handleDown(e:MouseEvent):void
{
selectionTool = new SelectionBase();
selectionTool.addEventListener("UPDATE", handleToolUpdate);
selectionTool.x = mouseX;
selectionTool.y = mouseY;
addChild(selectionTool);
}
private function handleToolUpdate(e:Event):void
{
// logic to determin if items are within selection goes here
}
}
}
I've tried using collision detection by means of BitmapData and even using collision libraries like CDK but I cant get anything to work. Anybody have an idea what I should use in the handleToolUpdate(e:MouseEvent); ? Thanks!
Update:
I'll break it down. Basically I am trying to create a prototype of the BumpTop Lasso or Selection tool.
I need help in finding out which objects either collide or have a point within the bounds of the drawn lasso.
I have upload what I have so far to my server here : http://labs.reyco1.com/bumptop/SelectionToolPrototype.html. You can see the source by right clicking and selecting "View Source".
Like I said in my earlier post, I tried using Bitmapdata collision testing and even tried using the Collision Detection Kit to no avail. Thanks in advance.
Loop through the display object you are attaching your random sprites to, and using for each, check their value of hitTestObject against your selectionTool instance.
Here are the Adobe docs for hitTestObject():
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#hitTestObject%28%29