Tag: flash

Entries for tag "flash", ordered from most recent. Entry count: 7.

Warning! Some information on this page is older than 5 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Pages: 1

# Calculating AABB of a Rotated 2D Rectangle

Jun 2010

Today I've solved an interesting geometrical problem of calculating an AABB rectangle (Axis-Aligned Bounding Box) around an oriented rectangle (rotated by an angle) in 2D.

AABB of a rotated 2D rectangle

It seems simple but it's easy to come up with suboptimal solution like calculating all 4 corners of the rotated rectangle or calling sin and cos functions multiple times. So I've coded a simple demonstration in ActionScript 3 (Flash). Here is my algorithm:

Input data:

// Center position of the rectangle.
private const m_PosX : Number, m_PosY : Number;
// Half-width and half-height of the rectangle.
private const m_HalfSizeX : Number, m_HalfSizeY : Number;
// Rectangle orientation, in radians.
private var m_Orientation : Number;


// corner_1 is right-top corner of unrotated rectangle, relative to m_Pos.
// corner_2 is right-bottom corner of unrotated rectangle, relative to m_Pos.
var corner_1_x : Number = m_HalfSizeX;
var corner_2_x : Number = m_HalfSizeX;
var corner_1_y : Number = -m_HalfSizeY;
var corner_2_y : Number =  m_HalfSizeY;

var sin_o : Number = Math.sin(m_Orientation);
var cos_o : Number = Math.cos(m_Orientation);

// xformed_corner_1, xformed_corner_2 are points corner_1, corner_2 rotated by angle m_Orientation.
var xformed_corner_1_x : Number = corner_1_x * cos_o - corner_1_y * sin_o;
var xformed_corner_1_y : Number = corner_1_x * sin_o + corner_1_y * cos_o;
var xformed_corner_2_x : Number = corner_2_x * cos_o - corner_2_y * sin_o;
var xformed_corner_2_y : Number = corner_2_x * sin_o + corner_2_y * cos_o;

// ex, ey are extents (half-sizes) of the final AABB.
var ex : Number = Math.max(Math.abs(xformed_corner_1_x), Math.abs(xformed_corner_2_x));
var ey : Number = Math.max(Math.abs(xformed_corner_1_y), Math.abs(xformed_corner_2_y));

var aabb_min_x : Number = m_PosX - ex;
var aabb_max_x : Number = m_PosX + ex;
var aabb_min_y : Number = m_PosY - ey;
var aabb_max_y : Number = m_PosY + ey;

Files to download:
AabbTest01.swf - online Flash demo
AabbTest01.zip - full project source code

I believe it can be optimized further (not only by rewriting it in C++ :) Anyone knows how?

Comments | #math #flash Share

# ActionScript 3 Standard Library Primer

Apr 2010

I've recently blogged about the syntax of ActionScript 3 language. Today I'd like to present what I've learned about the Flash standard library, especially in terms of displaying graphics. The official documentation to this is avaiable as ActionScript 3.0 Language and Components Reference (offline version for download - multipage HTML packed in ZIP).

Main package for graphics-related classes is flash.graphics. When programming in Flash, you do not redraw whole screen every frame like you do in DirectX or OpenGL. Instead you create a persistent hierarchy of objects, change their parameters and they are automatically drawn and updated. Base class of all objects that can be placed in this hierarchy is flash.graphics.DisplayObject and the class that can have children (the composite design pattern appears here) is DisplayObjectContainer. DisplayObjectContainer has methods such as addChild or removeChild to manage subobject.

For example, knowing that Sprite class that is the base class of our Main class inherits from DisplayObjectContainer and the TextField class we use here inherits from DisplayObject, the simplest Flash application that shows anything may look like below. The display object hierarchy here is: main object of the Main class with the tf object of TextField class inside, added as a child.

Read full entry > | Comments | #flash #rendering Share

# Block Wizard - My First Flash Game

Apr 2010

Just like tourists visit new places and see new cultures, programmers like to learn new languages and API-s. I've been recently coding in Flash and here is my first game made in this technology. As most of the Flash productions, it is available for free and can be played online via web browser.


Discuss @ forum.gamedev.pl [pl].

Comments | #flash #productions #games Share

# The Beauty of Sorted Arrays

Mar 2010

A one-dimmensional array (also called vector) is very simple data structure. We were taught that inserting or deleting elements in the middle of the array is slow because we have to move (by rewriting) all following elements. That's why books about C++ teach that for sorted collections - those who provide fast search operation - it's better to use containers like std::set or std::map.

But those who code games in C++ and care about performance know that today's processors (CPU) are very fast in terms of doing calculations and processing lots of data, while access to the RAM memory becomes more and more kind of a bottleneck. According to great presentation Pitfalls of Object Oriented Programming by Tony Albrecht from Sony, a cachce miss (access to some data from the memory which are not currently in CPU cache) costs about 400 cycles! Dynamic memory allocation (like operator new in C++) is also a slow operation. That's why data structures that use separate nodes linked with pointers (like std::list, std::set, std::map) are slower than std::vector and it's often better to keep a sorted collection of elements in a vector, even if you have hundreds or thousands of elements and must sometimes insert or delete them from the middle.

Unfortunately, C++ STL doesn't provide a "std::ordered_vector" container that whould keep items sorted while allocating single chunk of continuous memory. We have to do it by ourselves, like this:

First, we have to choose a way to compare elements. There are multiple solutions (read about comparators in C++), but the simplest one is to just overload operator < in your element structure.

#include <vector>
#include <string>
#include <algorithm>

struct Item
  int Id;
  DWORD Color;
  std::string Name;

  Item() { }
  Item(int id, DWORD color, const std::string name)
    : Id(id), Color(color), Name(name) { }

  bool operator < (const Item &rhs) const { return Id < rhs.Id; }

typedef std::vector<Item> ItemVector;

ItemVector vec;
Item item;

Here is how we insert an item into sorted vector:

item = Item(1, 0xFF0000, "Red");
ItemVector::iterator itToInsert = std::lower_bound(
  vec.begin(), vec.end(), item);
vec.insert(itToInsert, item);

Unfortunately we have to deal with iterators instead of simple indices.

To check if the vector contains element with particular Id:

item = Item(1, 0, std::string());
bool contains = std::binary_search(vec.begin(), vec.end(), item);

Here come another nuisances. We have to create full Item object just to use its Id field for comparison purpose. I'll show tomorrow how to overcome this problem.

It's also annoying that binary_search algorithm returns bool instead of iterator that would show us where the found item is. To find an item and determine its iterator (and from this its index) we have to use lower_bound algorithm. This algorithm is very universal but also hard to understand. It quickly searches a sorted collection and returns the position of the first element that has a value greater than or equivalent to a specified value. It was perfect for determining a place to insert new item into, but to find existing element, we have to use it with this if:

item = Item(1, 0, std::string());
ItemVector::iterator findIt = std::lower_bound(vec.begin(), vec.end(), item);
if (findIt != vec.end() && findIt->Id == item.Id)
  size_t foundIndex = std::distance(vec.begin(), findIt);
  // Not found.

And finally, to remove an item from the vector while having index, we do this trick:

size_t indexToDelete = 0;
vec.erase(vec.begin() + indexToDelete);

Well, C++ STL is very general, universal, powerful and... very complicated, while standard libraries of other programming languages also have some curiosities in their array classes.

For example, ActionScript 3 have single method to insert and remove items:

function splice(startIndex:int, deleteCount:uint, ...  values):Array

To delete some items, you pass non-zero deleteCount. To insert some items, you pass them as values parameter.

In .NET, the System.Collections.Generic.List<T> class (which is actually an array, the name is misnomer) has very smart BinarySearch method. It returns the "zero-based index of item (...), if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.". It can be used to both find existing item in the array or determine an index for a new item, like:

int index = myList->BinarySearch("abc");
if (index < 0)
  myList->Insert(~index, "abc");

See also: My Algorithms for Sorted Arrays

Comments | #algorithms #c++ #stl #.net #flash Share

# My First Flash Game

Mar 2010

I'm currently coding a small game in Flash (ActionScript 3.0). I've decided not to make an "engine-like" game with moving objects and precise collisions, but to start with something based on a grid, with turn-based gameplay. Up to this point there is no menu or nice UI and I don't even have a name for this game yet, but I already have much of the gameplay mechanics with many interesting features and perspectives for enabling many levels, as well as some interesting spells that can be cast when enough mana is available :)

Comments | #productions #flash #games Share

# ActionScript 3 Language Syntax Cheatsheet

Feb 2010

I started my Flash learning from reading about the ActionScript 3 language syntax from the "Learning ACTIONSCRIPT 3.0". Here is my quick-and-dirty sketch of a language syntax cheatsheet. I assume you are already familiar with programming in C++ and/or Java, so I emphasize differences.

Some background: ActionScript language comes from ECMAScript, which means it has syntax very similar to JavaScript, which in turn resembles C++ or Java. It's a case-sensitive language. It significantly evolved from version 1 through 2 until 3. It started as very dynamic, scripting-like language with dynamic data types and prototype-based object model (like in JavaScript or Lua). But now it looks more "serious" with the ability to define classes and compilation-time type checking (more like in C++ or Java).

Ending statements with semicolon ; is optional in ActionScript. Comments look exactly like in C++ - we have single line comments after // and multiline ones between /* and */. We also have many control statements looking just like in C++ - if, switch, while, do-while, return, break, for, continue. Interestingly, we can but labels into code like in C++ and then reference them in break and continue.

There are exceptions available, so we can use try-catch-finally blocks and throw exceptions like this:

throw new Error("Invalid email address");

Source code consists of packages with classes inside them, like:

package MyPackage1 {
  public class MyClass1 {

There can be only one public class inside a source file (default file extension is .as) and it has to have same name as the file name.

There can also be raw code (any statements, e.g. function calls) outside function definitions, like inside a class, a package or even at the top level. They are executed at program start.

Here is how you define variables (local variables or class fields):

var i1:int;
var s1:String = "abc";
var x:Number = 1, y:Number = 2.5;

You can also define constants:

const MyConst1:uint = 0xDEADC0DE;

Scoping rules for variables are similar to C++, so you can have static and normal class fields, as well as method parameters and local variables inside methods. There is a difference that {} blocks inside code do not create nested naming scope.

Primitive intrinsic data types are:

Complex intrinsic data types are: Array, XML, XMLList, Date, Function, RegExp, Object. Variables of these types are always passed and assigned by reference. Of course there is no manual memory management, the language has a garbage collector.

Variables are automatically initialized with default values. For int and uint it's 0, for Number it's NaN (!), for Boolean it's false, for Object and String it's null.

Here is how you define functions (methods). The example below is an event handler - events are widely used in Flash. There is an event for MOUSE_DOWN, MOUSE_MOVE, as well as ENTER_FRAME - called every frame, for example 30 times per second (sounds familiar? :)

private function OnMouseMove(event:MouseEvent):void

Default parameter values are supported, just like in C++ (and opposite to C#). There is also a rest operator ... available to enable passing any number of arguments.

Available attributes for classes are: internal (the default), public, dynamic (methods and properties can be added in runtime - see below), final (cannot be inherited). Attributes for class members are: internal (default), private, protected, public, static or a namespace name (see below).

Calling constructor of a base class can be done with super() keyword. If not explicitly called, the constructor of the base class is automatically called at the beginning of our constructor.

Methods do not need to be explicitly declared as virtual, but overriding them in subclasses requires override keyword. Method can also be declared as final so it cannot be overriden.

Because classes are organized inside packages, we have to either qualify them with full path like flash.events.MouseEvent, or import them into global namespace with:

import flash.events.*; // Importing everything from this package
import flash.events.MouseEvent; // Importing single class

When it comes to operators, we have whole bunch of standard arithmetic, logical and bitwise operators available similar to C++ or Java:

String concatenation is + which is quite intuitive, but not so obvious (as PHP use dot . for this purpose and Lua uses double dot ..). Object-oriented operators are also available (as in every modern and comfortable language - C++ is not one of them :P), like "is" and "as". Operator "as" returns null if cast is not possible.

Explicit type casting is done this way: Int(myString1). These are actually global functions, not type casting operators. Casting string to a numeric type does parsing so characters are converted to number. Strings with numbers saved in hexadecimal form like "0x123F" are also supported. Casting Boolean to String returns "true" or "false". Casting String to Boolean returns false if string is null or empty "".

ActionScript supports interfaces. Thay are like classes, but have to use "interface" keyword instead of "class" and have some restrictions. Class inheritance is done with the "extends" keyword and subclassing interfaces with "implements" keyword.

ActionScript provides very nice syntax for declaring so called getters and setters - class properties that work like methods, but can be used like fields. Here is an example:

private var privateProperty:String;
public function get publicAccess():String {
  return privateProperty;
public function set publicAccess(setValue:String):void {
  privateProperty = setValue;

Enums have not explicit support in ActionScript. One should declare a class instead with static constants of type uint, String or any other.

public final class PrintJobOrientation
  public static const LANDSCAPE:String = "landscape";
  public static const PORTRAIT:String = "portrait";

Function in ActionScript is a type, so functions can be assigned to variables, passed and returned. They are closures, which means they remember the context from which they come, including local variables (for nested functions) or object properties (for class methods extracted from objects). Example:

var traceParameter:Function = function (aParam:String) { trace(aParam); }

Arrays can be initialized with [] parentheses, like:

var seasons:Array = ["spring", "summer", "autumn", "winter"];

Basic text printing to the debug output can be done with trace function, e.g.:

for (var i:uint = 0; i < 10; i++)

There are also two loop instructions to iterate over array elements or dynamic object properties. The for-in loop iterates over keys in array or property names in object:

var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
  trace(i + ": " + myObj[i]);

The for-each loop iterates over values in array or property values in an object:

var myObj:Object = {x:20, y:30};
for each (var num:int in myObj)

The example above also shows dynamic object with arbitrary properties put inside during construction with {} operator. You can also dynamically add and delete properties of an existing object, like:

myObj.z = 10;
myObj['z'] = 10;
delete myObj.z;

To use your own class this way, you have to define it with dynamic keyword.

There is another dynamic feature still existent in ActionScript 3 - untyped (dynamically typed) variables. They are defined with asterisk * instead of type name.

var dynVar:*;
dynVar = 10;
dynVar = "Foo";

ActionScript has special syntax support for regular expressions with / operator, e.g.:

var myRegExp:RegExp = /foo-\d+/i; 
trace(myRegExp.exec("ABC Foo-32 def.")); // Foo-32

It looks very crazy for me that ActionScript accepts XML embedded just inside the code like an intrinsic type.

var employee:XML =

XML nodes can be addressed intuitively like in XPath, because language supports XML operators: @ . .. {} [] delete. For example:

var myXML:XML = <item id="42">
  <catalogName>Presta tube</catalogName>
trace(myXML.@id); // 42

Files (e.g. graphics or sound) can be embedded into classes with so called embedded asset classes, as in the example:

[Embed(source="sound1.mp3")] public var soundCls:Class;
public function SoundAssetExample()
  var mySound:SoundAsset = new soundCls() as SoundAsset;
  var sndChannel:SoundChannel = mySound.play();

Packages in ActionScript work like namespaces in C++, but ActionScript also have namespaces. They do something completely different though and they are the most crazy thing I can see in the syntax of this language. They are the way to define your own class member visibility specifiers next to standard keywords like public, private, protected and internal. For example:

class Class1 {
  public namespace Namespace1;
  public function Method1():void { }
  Namespace1 function Method2():void { }

Comments | #flash Share

# Learning ActionScript - TestProject02

Feb 2010

So I now learn ActionScript 3 in my free time at home. I think such technology is worth knowing as it has many adventages - the language is easy so I turn my ideas into code very fast, as well as present them online so you don't have to download and run any real application to see it working. Of course it's not a high-performance 3D technology and I always feel a bit limited when I code in a language with no fast, direct access to raw memory bytes through pointers, but it's sufficient for many purposes. As I learn it, I have lots of ideas about how could I use it to create some interesting graphics or gamelay experiments, presentations (e.g. for learning and understanding some geometry math) or even entire games. And from all these online technologies like Java or JavaScript + AJAX, I think I prefer Flash the most.

How exactly do I learn it? First of all, there is this big and expensive Flash with graphical design environment, but I don't use it. I use pure ActionScript 3 programming language (the version is very important here) and FlashDevelop - a great IDE for Windows that looks fast and lightweight but is very convenient and powerful at the same time (I wish IntelliSense in Visual C++ worked like this).

I've been looking for a tutorial to learn the language, but I haven't found anything that would satisfy me, so I've downloaded official documentation from Flash CS3 resources. Until now I've read "Learning ACTIONSCRIPT 3.0" (there is a PDF version for download) and of course I always have the Language Reference opened (there is a downloadable version ActionScriptLangRefV3.zip as ZIP with multipage HTML inside).

Here is my first application - Conway's Game of Life. Use left mouse button to interact.

You can download the entire FlashDevelop project here: TestProject02.zip or see the main script online: Main.as.

Comments | #flash Share

Pages: 1

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2021