AS3 Is it possible to duplicate a Shape object? - actionscript-3

I'm trying to make a shape available for duplicating. Here's an explanation of what I've done, what I'm trying to do, and where I'm stuck:
Drew a shape manually in the Flash IDE (paintbrush).
Created a new movieclip containing the shape; exports as a class.
Instantiate the class (var mc:MovieClip = new shapeMovieClip()).
Add a reference to the shape in mc that I want (var myShape:Shape = mc.getChildAt(0) as Shape;
This works perfect and I now have my shape, but how can I duplicate it without instantiating the parent MovieClip class - is it possible?
I've tried creating a new shape and using the copyFrom() graphics method with no avail, I believe this method just copies draw calls when they're made on the referenced graphics and instead I just have a reference of a shape that's already been drawn.
Right now I'm extending the movieclip as a sprite instead, instantiating, pulling the shape from the parent and saving its reference, and then nulling the sprite. Does anyone know of a better, more lightweight, strategy for duplicating Shapes in this manner?

Basically depends on whether you need to scale your shapes. If you don't, and you can work it out with a fixed sized bitmap representation of the shape, then you will get much better performance drawing your shape to a BitmapData (it's called rasterisation) and instanciating Bitmap objects (as other commenters have pointed out). The code would go something like this:
var base:Sprite = new shapeMovieClip();
var bmd:BitmapData = new BitmapData(base.width, base.height, true, 0);
bmd.draw(base);
var clip1:Bitmap = new Bitmap(bmd);
var clip2:Bitmap = new Bitmap(bmd);
If you do need to scale the clips, you will get pixelation using bitmaps. When scaling down Bitmap.smoothing can help to some extent (also when rotating), but if you need to scale up, you will probably have to use some kind of mip-mapping. This is basically creating a few bitmaps of the shape at different scale levels, and then swap them depending on the current scale. Coding this has some complexity (using a helper parent to adjust the scale can help) but it will definitely perform better than using many shape symbols (with or without a sprite parent).

This is very old, but it still comes up high in Google, so I just wanted to share a true shape duplicating method:
var shapeonstage:Shape = shapeMadeInIDE;
var g:Vector.<IGraphicsData> = shapeonstage.graphics.readGraphicsData();
var shapecopy:Shape = new Shape();
shapecopy.graphics.drawGraphicsData(g)
And boom. It works. Had to share this because it would have helped me a looooong time ago and in so many ways.
UPDATE:
There is some clarification I'd like to add why you would want to use this method, for duplicating AND for storing references to Shapes that are within an swf.
If you target a Shape object on the stage or in a movie clip, the Flash Rendering engine does something strange. It will RECYCLE Shape objects to render new graphics thus making your Shape reference point to a COMPLETELY different rendering.
For example:
Create an fla with a movieclip.
Inside the movie clip make 10 frames.
On each frame, draw a different shape
In your code, get a reference to the shape (The Shape on Frame 1)
Draw and verify your shape (draw to a bitmap then put the bmp on stage)
Now let the flash engine play for 5 frames
Draw and verify your shape again
The second time you draw your shape without EVER reassigning your shape reference, will SOMETIMES yield a completely different shape.
Just know, this little quirk can leave you pulling your hair out if you don't know what you're looking for :)

Related

Removing Color from Sprite ActionScript

My project loads SWF files using the Loader class, and then loads Sprite objects from those child files. Each sprite has a specific green color, and I want to substitute all pixels of one color for transparent ones.
I can re-compile these Sprites as objects of the BitmapData class, to simplify things, but I'm looking for any way that avoids operating the objects pixel-by-pixel. I'm guessing that I can use some kind of bitmap filter, but I'm just not familiar enough with ActionScript to know specifics.
try threshold with bitmapData of that Sprite.
Before                           After √
var bmd:BitmapData = new BitmapData(sprite.width, sprite.height, true, 0x0);
bmd.draw(sprite);
bmd.threshold(bmd, bmd.rect, new Point(), "==", 0xff00ff00); // 0xff00ff00 = GREEN
you may change the green color, also you are free to setting more range of colours to be transparented, for example, some kind of detecting smooth corners like this:
just need to play with operation argument of threshold, i used "==", but many others available.
refrences :
Adobe
Doc

AS3 3D-Renders slowly

Good time.
As you know,3d shapes in as3 are flat surfaces and we can make polyhedrons by moving and rotating that flat surfaces in the three dimensions.
BUT......
what about Non-Polyhedra shapes(spheres,cylinders)??
One way is to make surfaces using flat shapes.
An example to make a cylinder; you can copy this code to see what happens:
import flash.display.Sprite;
const angle:Number=Math.PI/180;
var numOfSides:uint=200;
//number of sides around
var pixWidth:uint=4;
//width and height of sides
var cldHeight:uint=20;
//height of cylinder
var s:Sprite=new Sprite();
s.graphics.beginFill(0xffffff*Math.random());
s.graphics.drawRect(0,0,pixWidth,pixWidth);
addChild(s);
this.cacheAsBitmap=true;
for(var n:uint=1;n<cldHeight;n++){
for(var i:uint=1;i<numOfSides;i++){
var prevS:Sprite=s;
s=new Sprite();
s.graphics.beginFill(0xffffff*Math.random());
s.graphics.drawRect(0,0,pixWidth,pixWidth);
s.x= prevS.x + Math.cos(-prevS.rotationY*angle)*s.width;
s.y=n*pixWidth;
s.z=prevS.z+Math.sin(-prevS.rotationY*angle)*s.width;
s.rotationY=-i*(360/numOfSides);
s.cacheAsBitmap=true;
addChild(s);
}
s=new Sprite();
}
and my problems:
Flash now renders EXTREMELY slow :-(
please improve this code or suggest a better one.
A few minor notes on the code:
Don't forget to end the fill when you're done(e.g. s.graphics.endFill() after the drawRect() call)
cacheAsBitmap works well for display objects without rotation applied if I can remember
4000 (200*20) Sprites with 3D transformations applied might push the display list a bit.
Remember to also sort the sprites
I recommend checking out these resources:
Flash & Math blog Icosahedron 3D tutorial
Senocular's exhaustive FP10 Drawing API article (using drawTriangles() would be more efficient since you'll have a single Sprite on the display list)
If you want to draw the vertices, it should be pretty fast to draw the 3D points projected to 2D on a bitmap
All of the above use Flash Player 10's features, but it might be much simpler to use a 3D API like Away3D which already provides easy ways to draw cylinders (with textures) at very high speeds(especially newer versions that use hardware acceleration)

How do i create an animation in AS3?

I am making a game in AS3 for a school project (using the AIR api). I have about a year's worth of experience in AS3, so i would say i'm proficient but not an expert. Anyway, i have never attempted to do sprite animations in AS3 and i'm not quite sure how to approach it.
If i create a list of bitmaps and call addChild() and removeChild() to display each frame of the animation, it would affect the framerate as these functions are not very efficient (i have tried this before and it tanked my framerate if i had too many animations going at once). I have also tried creating a list of BitmapData objects, adding a bitmap to the display list, and then pointing it to a different BitmapData each frame, but this does not seem to work at all.
So what is the best way to do this? In XNA, for example, i would create a sprite class that draws to the screen using a sprite batch, then i would create a list of sprite objects and cycle through them to create the animation. Is there any way to achieve a similar result in actionscript?
First (simple) method: you can just use multi-frame MovieClip for animation. Put an image in each frame, put a MovieClip on the stage and that's all. You can control this animation using play(), stop(), gotoAndPlay(), gotoAndStop(). It will work without much problems for a generic platform game (I did that myself long ago).
Second (advanced) method: use bitmap blitting. For each animation, create a bitmap image that holds each frame of the animation. Use this image as a source for copying pixels into your current animated object. You just need to copy a particular rectangle area inside a source bitmap that corresponds to the current frame.
The actual blitting happens here
destinationBitmapData.copyPixels(sourceBitmapData, areaRectangle, destinationPoint);
Where destinationBitmapData is your "canvas" that you're blitting to; sourceBitmapData is the source image holding all animation frames; areaRectangle is the Rectangle inside the source image defining which area to copy; destinationPoint is left-top coordinate of the copy area in your canvas.
The destination canvas can be just one small object (like your game character that is moving around) or the entire game screen with all objects. I.e. instead of blitting and adding each object separately, you can just have one big canvas and blit any necessary parts directly to it.
That said, there is already a number of various ready-made engines that use blitting and even advanced techniques like 3D acceleration for 2D sprites.
One of them is Starling.

Spritesheet with mask or separate image files?

I'm making an animation of a 2D character that can walk, run, jump, bend,...
Would it be better to load one big 'spritesheet' with all the animations and just use a mask, or would loading separate files (walk, run,...) be better because you're not using a mask on such a big image every frame?
I'm not using the Stage3D features with a framework like Starling because I think the normal flash display API is fast enough and has much less bugs than the relatively new GPU frameworks.
Blitting just the character (using lock(),copyPixels(),unlock()) works pretty well.
private function updatePixels():void{
//update sprite sheet copy position based on the frame placements ons prite sheet
position.x = spriteSourceData[currentFrame].x + offset.x;
position.y = spriteSourceData[currentFrame].y + offset.y;
//draw into the bitmap displayed
displayData.lock();
displayData.fillRect(displayData.rect, 0x00FFFFFF);//clear
displayData.copyPixels(sourceData, spriteData[currentFrame], position);//copy new frame pixels
displayData.unlock();
}
//a bit about vars:
position:Point
spriteSourceData:Vector.<Rectangle> - from parsed Texture Packer data
offset:Point - front view and side view animations weren't always centred, so an offset was needed
displayData:BitmapData - pluging into a Bitmap object displayed
sourceData:BitmapData - the large sprite sheet
currentFrame:int - image index on the sprite sheet
I've done this on an older project writing a custom class loosely following what I've learned from Lee Brimelow's tutorial series Sprite Sheets and Blitting (Part 1,Part 2, Part 3)
In short, you'd use two BitmapData objects:
a large sprite sheet
a small image to display just the character (size of the largest character bounding box) to copy pixels into
In my project I had a character with front and side animations and for the sides I've used one set of animations and used the Matrix class to flip(scale and translate) the side animation accordingly. I've used TexturePacker to export the image sequence as a sprite sheet and the frame data as well as a JSON object. There is native JSON support now, so that's handy. Texture Packer isn't free but it's really worth the money (affordable, fast and does the job perfectly). I haven't used Flash CS6 yet but I imagine it's also possible to import your image sequence and export a spritesheet with the new feature.
In my experience the rule "the simpler the display list the better the performance" generally applies. Which means you should use the most specific display object that will do the job (don't use a Sprite when a Shape would be sufficient or favor Bitmaps over vectors where it makes sense).
The most extreme version of this is to only have one Bitmap display object on the stage and use copyPixels to draw all game objects into it every time you want to update the screen. It doesn't really matter what the source in the copyPixel call is, it could either be a large BitmapData acting as a sprite sheet or a small BitmapData objects representing a single frame in an animation. This method is really fast and you could easily have many hundreds of objects on screen at the same time. But using copyPixels means you can't scale or rotate a game object, so for those cases you would have to fall back to the much slower draw() method. Of course this single Bitmap method is not suitable for games where you need to attach mouse events to specfic objects in the game, but works well for shoot'em ups or platform games.
To answer your question, I think you will get better performance by using a single Bitmap display object to represent the player and a collection of BitmapData objects for all the animation frames. Then you can just change the Bitmap's bitmapData property to the frame you want to display. You can still load a large spritesheet png and then plit it up into a series of BitmapData objects during the initialization of the game.

Actionscript 3 pixel perfect collision. How to? (learning purposes)

I know that there are people out there creating classes for this (ie http://coreyoneil.com/portfolio/index.php?project=5). But I want to learn how to do it myself so I can create everything I need the way I need.
I've read about BitMap and BitMapData. I should be able to .draw the MovieClips onto a BitMap so I could then cycle the pixels looking for the collisions. However, It's weird and confusing dealing with the offsets.. And it seams like the MyBitMap.rect has always x = 0 and y = 0... and I can't seam to find the original position of the things...
I'm thinking of doing a hitTestObject first, then if this was positive, I would investigate the intersection betwen the movieclips rectangles for the pixel collisions.
But then there is also another problem (the rotation of movieclips)...
...I need some enlightment here on how to do it.
Please, any help would be appreciated..
If you're using BitmapData objects with transparency you can use BitmapData.hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean.
You'll have to change from global coords to the local BitmapData coords which will require a bit of math if it is rotated. That's easily achieved (look up affine transform for more info on wiki):
var coordTransform:Matrix = new Matrix();
coordTransform.rotate(rotationRadians);
coordTransform.translate(x, y);
coordTransform.transformPoint(/* your point */);
A classic reference for pixel perfect collision detection in flash is this Grant Skinner's article. It's AS2, but the logic is the same for AS3 (there are ports available if you google a bit).
If I recall correctly, this particular implementation worked as long as both tested objects had the same parent, but that can be fixed.
About BitmapData x and y values, I understand it could be confusing; however, the way it works makes sense to me. A BitmapData is just what the name implies: pixel data. It's not a display object, and cannot be in the display list; so having x or y different than 0 doesn't really make sense, if you think about it. The easiest way to deal with this is probably storing the (x,y) offset of the source object (the display object you have drawn from) and translate it to the global coordinate space so you can compare any objects, no matter what's their position in the display list (using something like var globalPoint:Point = source.parent.localToGlobal(new Point(source.x,source.y)).
I've previously used Troy Gilbert's pixel perfect collision detection class (adapted from Andre Michelle, Grant Skinner and Boulevart) which works really well (handles rotation, different parents, etc.):
http://troygilbert.com/2007/06/pixel-perfect-collision-detection-in-actionscript3/
http://troygilbert.com/2009/08/pixel-perfect-collision-detection-revisited/
and from there he has also linked to this project (which I've not used, but looks really impressive):
http://www.coreyoneil.com/portfolio/index.php?project=5
I managed to do it after all, and I already wrote my class for collision detections,/collisions angle and other extras.
The most confusing process is maybe to align the bitmaps correctly for comparing. When whe draw() a movieclip into a a BitmapData, if we addChild() the corresponding Bitmap we can see that part of it is not visible. it appears to be drawn from the center to right and down only, leaving the top and left parts away from beeing drawn. The solution is giving a transform matrix in the second argument of the draw method that aligns the bitmap and makes it all be drawn.
this is an example of a function in my class to create a bitmap for comparing:
static public function createAlignedBitmap(mc: MovieClip, mc_rect: Rectangle): BitmapData{
var mc_offset: Matrix;
var mc_bmd: BitmapData;
mc_offset = mc.transform.matrix;
mc_offset.tx = mc.x - mc_rect.x;
mc_offset.ty = mc.y - mc_rect.y;
mc_bmd = new BitmapData(mc_rect.width, mc_rect.height, true, 0);
mc_bmd.draw(mc, mc_offset);
return mc_bmd;
}
in order to use it, if you are on the timeline, you do:
className.createAlignedBitmap(myMovieClip, myMovieClip.getBounds(this))
Notice the use of getBounds which return the rectangle in which the movie clip is embedded. This allows the calculation of the offset matrix.
This method is quite similar to the on shown here http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
By the ways, if this is an interesting matter for you, check my other question which I'll post in a few moments.