How to develop high-performance flash game? - actionscript-3

1.How to load image resources? And in which case we should use "[Embed]" to insert resources?
2.which technology can improve the performance of the game flash game development ?

Use loaders to access external images, like this:
private function init():void
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaderCompleteEvent);
loader.load(new UrlRequest("someImage.jpg"));
addChild(loader);
}
private function handleLoaderCompleteEvent():void
{
//Do something.
}
regarding the technologies: if you want some nice animations in your game, use the TweenLite-library, which is awesome for animations. If you want to use 3D, use Papervision3D or away3D, but that requires some studying and getting to know the libraries, as where TweenLite is easily accessible and used.

Doing more with bitmaps, and in some cases, it might help to compile computationally intensive routines from C code using Alchemy (for collision detection and physics issues, especially).
More than anything else though, you will benefit from using the Flash Builder (or 3rd party) profiler, and other forms of benchmarking to figure out what you need to improve on. There is no substitute for knowing the limitations of your platform and having a nice bag-o-tricks from experience.

I find that it all comes down to rendering in the end.. The more vector graphics you use the slower it gets. It makes a ridiculous difference for me if I either move to sprite sheets, or create a class that uses a single MovieClip as a resource for multiple BitmapData objects to draw from.
What I mean is: Say you have a MovieClip for a game enemy like a ship or something. Firstly, create one instance of the MovieClip somewhere that is easily accessible. From here, all of your Ship objects could extend Bitmap. Another feature would be maybe a rendering controller that applies rotation and sets the frame of your ship movieclip. From here, Ship could work similar to this:
public class Ship extends Bitmap
{
/**
* Constructor
*/
public function Ship()
{
/**
* 1. specify the source movieclip thats been set up in RenderClassThing
* 2. set the rotation to 45 degrees
* 3. set frame of source movieclip to 4
*/
RenderClassThing.prepare(shipMC, 45, 4);
// applies bitmap
bitmapData = RenderClassThing.getBitmapGraphics(shipMc);
}
}
This will make a massive difference if you use a lot of vector graphics.

Related

How drag a Sprite smoothly on-screen in actionscript

First of all, my question is basically the same as this one:
How to drag an image to move it smoothly on screen, with ActionScript?
I want my dragged Sprites to keep up with the mouse on-screen, smoothly, without lagging behind.
And I notice that in the old ActionScript 3 Cookbook from way-back-when that they used a similar solution for their DraggableSprite as was used in the above link. Namely, use the stage instance to listen for the MouseMove event and then read from the event.stageX and stageY properties.
I've done that.
But my Sprite still doesn't stay locked with the mouse cursor. It lags behind. I feel like I must be missing something. However, if the solution posted above (ie listen for stage's MouseMove and use event.stageX/Y) is still current and the problem I'm describing should not be occurring, please also let me know. Even though it's not supposed to work, I've tried event.updateAfterEvent() and it also doesn't seem to have any positive effect.
Any help or advice would be greatly appreciated.
Here's a simple example of how I've written the handlers. It should work as-is if pasted into a new project.
I should also add that I'm compiling this as a desktop application using Adobe AIR. Would the run time be a factor???
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
[SWF(width="1280", height="720", frameRate="30")]
public class test_drag extends Sprite {
private var testDragSprite:TestDragSprite;
public function test_drag() {
super();
graphics.clear();
graphics.beginFill(0x0000FF);
graphics.drawRect(0, 0, 1280, 720);
graphics.endFill();
testDragSprite = new TestDragSprite();
addChild(testDragSprite);
testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, testDragSprite_mouseHandler);
testDragSprite.addEventListener(MouseEvent.MOUSE_UP, testDragSprite_mouseHandler);
}
private function testDragSprite_mouseHandler(e:MouseEvent):void {
switch (e.type) {
case MouseEvent.MOUSE_DOWN: {
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
break;
}
case MouseEvent.MOUSE_UP: {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
break;
}
}
}
private function mouseMoveHandler(e:MouseEvent):void {
//-20 to keep the sprite centered on the mouse
testDragSprite.x = e.stageX - 20;
testDragSprite.y = e.stageY - 20;
//e.updateAfterEvent(); //strange effect, but doesn't solve the problem.
}
}
}
import flash.display.Sprite;
internal class TestDragSprite extends Sprite {
public function TestDragSprite() {
super();
graphics.lineStyle(1, 0xDDDDDD);
graphics.beginFill(0xFF0000);
graphics.drawRoundRect(0, 0, 40, 40, 12);
graphics.endFill();
}
}
There is always going to be a little lag, but:
The first two suggestions will make the most noticeable change to your code/performance.
Enable hardware graphics acceleration; edit your AIR application
descriptor file (xml) and set renderMode to Direct (or GPU). Consult
the Adobe Air help for details.
<!-- The render mode for the app (either auto, cpu, gpu, or direct). Optional. Default auto -->
<renderMode>direct</renderMode>
Use startDrag and endDrag to bypass your manual assignments in your mouseMoveHandler.
Replace :
testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, testDragSprite_mouseHandler);
testDragSprite.addEventListener(MouseEvent.MOUSE_UP, testDragSprite_mouseHandler);
With :
testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
testDragSprite.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
Add the new handlers:
private function mouseDown(e:MouseEvent):void {
testDragSprite.startDrag();
}
private function mouseUp(e:MouseEvent):void {
testDragSprite.stopDrag();
}
Increase your frame rate, but watch your CPU usage as your application/game becomes more complicated as you may need to lower it to allow your game logic enough time to complete between frames (otherwise you end up with what is called long frames, you can use the free Adobe Scout profiling tool to watch for these and lots of other things).
Add a frame rate HUD to your display so you can monitor when your actual framerate is lower than the requested framerate (this is for debugging)
If your game is 2d based, consider using the open-source Starling framework as all content is rendered directly by the GPU vs Flash's standard display list objects.
Just try the member function startDrag.
The Feathers UI library includes a drag-and-drop module. The answers above all use the 'old' display list which is not mobile-ready. If you want your code to work cross-platform you need a GPU framework (most popular is Starling on which Feathers is based, as well as most Adobe AIR games and Apps).

Actionscript 3: Drawing lines and bitmaps the right way

I'm just getting started with Flash/ActionScript and it seems to be the general consensus to create Sprites, Bitmaps, MovieClips, etc for various objects in order to represent pictures and other graphics.
However, the way I'm used to writing games and whatnot in other languages is to just loop repeatedly and each frame use something similar to the Graphics object to redraw the scene on the main Sprite. Is this how it's also done in Flash, and is it good practice? I can do it this way, but I'm wondering if there's some Flash ecosystem standard instead.
Here's an example of the way I'm used to:
public class MyApp extends Sprite
{
public function MyApp()
{
var t:Timer = new Timer(20);
t.addEventListener(TimerEvent.TIMER, update);
t.start();
}
public function update(e:TimerEvent)
{
this.graphics.clear();
//Rendering code and updating of objects.
}
}
Is this acceptable?
Well, it depends.
In Flash, you have the option of relying on the Flash Player's vector rasterizer and rendering system, which will figure out all the redrawing for you. For instance, you can draw once to a Sprite then simply apply transforms to the sprite (set x, y, width, height, rotation, scaleX, scaleY, transform.matrix, transform.colorTransform, etc). Any of these objects could be a vector shape or a bitmap, and you can also use cacheAsBitmap and cacheAsBitmapMatrix for even more redraw optimization. The Flash Player will only redraw areas that change, on the frame that they change. I would consider this the traditional "Flash way".
Using the Graphics API is just a programmatic way to create vector shape data. Think of it as a code alternative to drawing in the Flash IDE. You could draw using Graphics once when the object is created, or if you needed to change the actual shape (ie not just the transform) you are correct that you would clear() and redraw it. However, ideally you would not be doing that a lot. If you find yourself redrawing the shape a lot, you might want to move to a pre-rendered sprite-sheet approach. In that case you use BitmapData to more quickly copy pre-drawn pixel data to a Bitmap object. This is generally faster than relying on the vector rasterizer to render your Graphics commands, as long as you use the fast pixel methods like copyPixels(). This is probably closer to the sort of rendering systems you are used to in other platforms that don't have a vector rasterizer built in.
Lastly, it's worth noting that the newest (and fastest) way to render objects in Flash is completely different than all that. It's called Stage3D and it uses a completely different rendering pipeline than the vector rasterizer. It's powered by GPU rendering APIs, so it's blazing fast (great for games) but has no vector rasterizing abilities. It can be used for both 3D and 2D. It's a bit more involved to work with, but there are some useful frameworks to make it easier, most notably the Starling 2D framework.
Hope that helps.
The "Flash way" is to use EnterFrame event instead of using timer to draw. You must make your calculation whenever you want but let flash draw you scene.
It works the same way in actionscript.
public class App extends Sprite // adding "my" to identifier names doesn't add any information, so there's no real point in doing it
{
public function App()
{
addEventListener(Event.ENTER_FRAME, update); // "each frame"
}
private function update(e:Event):void //not just parameters of functions have a type, but also their return value
{
graphics.clear(); // no need for "this" here
//Rendering code and updating of objects.
}
}
Keep in mind that the Graphics API is vector based and as such will only draw so many things before dropping performance.
Sprite is a general purpose container, not to be confused with what the term "sprite" stands for in a sprite sheet.
What you are probably referring to when saying "main Sprite" is some rectangular region of pixels that you can manipulate.In this case, a BitmapData is what you want, which is displayed with a Bitmap object.
BitmapData does not offer a graphics property. Essentially, drawing vectors and manipulating pixels are treated separately in As3. If you want to draw a line in a BitmapData object, you'd have to first draw the line as a vector into a Sprite (or better Shape, if all you want to do is draw on it) using its graphics property, then use draw() of BitmapData to set its pixels according to the drawn line.

as3 creating a custom property in Emanuele Feronato's "Flash Game Development by Example"

I recently picked up Emanuele Feronato's Flash Game Development by Example to try and help expand my knowledge of game design and actionscript 3, and I'm stuck on the first chapter where we're building basically a memory match two game where you have ten sets of tiles and you try and match them up by clicking on them.
In the code I'm stuck on, Mr. Feronato is adding the tiles to the stage using a for loop and addChild, here's the code in particular:
// tile placing loop
for (i:uint=0; i<NUMBER_OF_TILES; i++) {
tile = new tile_movieclip();
addChild(tile);
tile.cardType=tiles[i];
tile.x=5+(tile.width+5)*(i%TILES_PER_ROW);
tile.y=5+(tile.height+5)*(Math.floor(i/TILES_PER_ROW));
tile.gotoAndStop(NUMBER_OF_TILES/2+1);
tile.buttonMode = true;
tile.addEventListener(MouseEvent.CLICK,onTileClicked);
}
// end of tile placing loop
In the 5th line, you can see that he creates a custom property of the tile variable called "cardType," but when I try and run the code I get the error "Access of possibly undefined property cardType through a reference with static type Tile." I have the class Tile extending MovieClip, and the main class extends Sprite, but as far as I can tell I've written the code exactly as in the book and can't get past this. I thought about just using a normal int variable cardType to hold tiles[i] but later on you use the cardType property on a mouse event so I'm a little stuck.
Has something changed in Flash that no longer allows you to create custom properties in this way? Or did I just do something stupid that I'm not catching.
As always, thank you so much for the help.
ActionScript supports dynamic classes, in which properties may be added during runtime. Without the dynamic keyword, a class is sealed, meaning its properties may not be altered.
MovieClip is an example of a dynamic class.
Instantiating a MovieClip from code (or MovieClip instance created in Flash Professional), adding this property would be supported:
var tile:MovieClip = new MovieClip();
tile.cardType = "custom value";
However from code, even if extending MovieClip you must add the dynamic keyword:
package {
import flash.display.MovieClip;
public dynamic class Tile extends MovieClip {
/* ... */
}
}
Now, you may add properties to your Tile instance:
var tile:Tile = new Tile();
tile.cardType = "custom value";

Practical way of getting a picture of a library object

I´m making a level creator for my platformer game on AS3. I´m looking for a way of getting a graphical representation of a library object on my .fla, so the user can insert that object on the world on the desired coordinate. What I mean with this is that I just want a picture of the first frame of the mc, without taking its properties and methods (without the need to make a .jpg containing that image), because that´s when problems begin to appear, and I just want the object functionality on play mode, not the level creator.
Let´s say, for example, a ball that bounces all the time by updating its location every frame. On the level creator I just want to get the ball picture to insert it on the desired location. If I take the whole ball object to the level creator it won´t stop bouncing and it will mess things up.
I hope I´m clear... I just want to know if there is a practical solution to this; if not then I´ll make a class where all the world objects would extend to, that has a init() function that initializes all the object functionality, so it´s called only on play mode and not on level creator. Thanks for reading anyway.
What you're doing wrong is adding functionality directly to the MovieClip.
Please read one of my previous answers that covers this concept in more depth.
MovieClips should be used for the display only, representing the graphics of an actual game class, for example:
public class Player
{
// Graphics that represent the Player.
protected var display:MovieClip;
// Constructor.
public function Player()
{
display = new PlayerMovieClip();
}
}
Anyways, once you fix that you can take a Bitmap sample of MovieClips using BitmapData and its draw():
// Assume that 'mc' is your MovieClip.
var sample:BitmapData = new BitmapData(mc.width, mc.height, true, 0);
sample.draw(mc);
// This is your image.
var texture:Bitmap = new Bitmap(sample);

Is it possible to create a MovieClip using ActionScript 3 code or MXML?

I'm using the Flex 3 SDK and the free FlashDevelop IDE.
As I don't have FlexBuilder or Flash CS4 Professional I cannot make MovieClips graphically.
So instead I want to create a simple MovieClip using code or MXML. For example, lets say I want to create a MovieClip with 3 frames, and load a bitmap into each frame to create a simple animation.
Is this possible? I've had a good google around and the only examples I can find are of loading existing MovieClips and adding them to a stage.
You can create a movieclip with this simple code:
var mc:MovieClip = new MovieClip();
stage.addChild(mc);
That is of cause just and empty movieclip, you can draw on it with graphics property (see here).
As far as I know there is no way to create frame with actionscript. Though there might be some undocumented methods. There are some functions that do not appear in the documentation (like the addFrameScript method).
I would say the best way (if you absolutly can not use the Flash CS4), would be to have a series of Loader objects, and the hide and show them on every in sequence.
Just put them in an array and listen for the enterFrame event.
You can load in the bitmaps in the Loader objects.
If you use the links and checkout the examples in the documentation, I think you should be able to figure it out.
As far as I've seen, there is no easy way to create a MovieClip in Flex which behaves in a way one might see as comparable to Flash's implementation MovieClip. But I don't think you really want a MovieClip to begin with. Flex does not really play well with non-flex objects. Yes, it is possible to add something to a UIComponent, but you are much better off working withing the Flex framework than doing workarounds.
I would use the mx:Image tag to load your images. It is generally the cleanest way to load an image into Flex. It will let you embed the object into the SWF at compile time, which means that you will not have to point to an outside file. I will caution about having too many embedded graphics -- that will kill your download time and possibly your performance.
If you are only interested in having an animation move or re-size, then I would use the Move and Resize objects which are native Flex Tweens.
Your best option might be to extend the UIComponent class, add a MovieClip as a child-component, and apply the settings from MXML via proxy. e.g.,
public function set movieFrames(value:Array):void {
for each(var b:Bitmap in value) {
//add bitmap to _movieclip object.
}
}
You want a Sprite not a MovieClip. And use time instead of frames. There's a Timer class and a getTimer() function. Use them.
create a class that extends/implements Sprite.
Add a Loader class.
Google it exactly how it's done. (flashtuts.com or sth like that).