## Archive for the 'Actionscript' Category

18
Dec
09

### Creating Mathematical Formulae from sample data using Excel

So you’re in Flash and want to move an item on the stage, rotate a camera or dynamically change a volume depending on another value. You could use the curves available in various Maths libraries, but you can spend a lot of time matching and applying constants.

A quicker – more accurate way can be to come up with your own formulae.

What!!? It is easy – you really don’t have to understand the mathematics, you can get Excel and Flash to do the heavy lifting for you.

Let me explain this by means of an example:
I was building a 3D application. I had a camera and needed it’s X rotation to be close to certain values depending on the camera’s position on the Z axis. I manually moved the camera into position and noted down samples of the values I required and placed them into Excel: One column for the z value and one for the required angle. – I only need a handful of samples to allow me to plot a regression trend line.

I now select the values on the spreadsheet and create an XY scatter chart. Great, my points are on the graph. I can see it makes a curve. In the ‘Chart’ drop down menu I now ‘Add Trendline…’. If I choose ‘Linear’ I get a straight line, but I want a curve so I can choose from a number of different methods. In this case ‘Exponential’ seems good. Select that and a look at the Options tab allows me to select ‘Display Equation on Chart’.

Now as soon as I press OK, I get my equation. Simple.

Regression Curve Formula in Excel from sample data

How do I represent this formula in Actionscript? Basically it is saying 202.62 times the exponential of 0.0014 times the chart’s x value. So in AS:

The final formula in Actionscript

As required, I have calculated the formula using the camera.z value and applied it to camera.rotationX. Now whenever the z value changes I have a smooth curve applied to rotationX.

Nice!

2nd Oct 2010:
A quick addition to this post. If a more complex curve is needed then a polynomial should be chosen. A polynomial can have multiple ‘orders’. This more orders you have the more compelx the curve can be. (Excel allows up to 6). A great thing about polynomials is speed. It is merely a series of multiplications which are very light on the processor.

So a polynomial trend gives you (for example) the formula:
109.13×4 – 265.48×3 + 125.34×2 + 40.012x + 2

To represent this in Actionscript I’d need to replace x4 (x to the power of 4) with the x value paramter – say delta – so x4 becomes delta * delta * delta * delta (or indeed Math.pow(delta,4)), and so on. The final formula would be:
109.13 * Math.pow(delta,4) – 265.48 * Math.pow(delta,3) + 125.34 * Math.pow(delta,2) + 40.012 * delta + 2

18
Nov
09

### Ranged Numbers. Non-Linear response curves for Sliders and TouchPads.

I’ve been building a few apps recently and have found that a linear response over a range of numbers has been a poor solution. I needed to be able to apply different response curves to user interface components (knobs, sliders, touchpads) as well as on screen display objects, characters, etc.

I needed a good name for the class, but instead came up with the pretty poor moniker ‘RangedNumbers’. I’ll change it when I come up with a better one.

So the idea is, a ‘ranged number’ is instantiated, initialised for the required range then a simple call with a value in that range will result with a percentage that can be applied to the intended recipient accordingly. I realised that an inverted curve would be handy too, so have added that functionality.

I have included exponential and powered curves as well as linear.

So to use the ranged number system:

//Instantiate and Initialise
var ranged_num:RangedNumber=new RangedNumber(min,max)
//Where min is the minumum number in the range and max is the maximum

//In use:
trace ( ranged_num.calculatedRangeNumber(value, curve_type, inverted) )
//Where:
// value is the value within the range to be calculated
// curve_type is the type of response curve.
// Curve types: RangedNumber.LINEAR, RangedNumber.EXPONENTIAL, RangedNumber.POWERED
// inverted is a boolean flag. True if the inverted response is required

I have put together two demos to show the RangedNumber class in action:

Firstly using a Slider component. Grab the slider and watch how the markers are represented on all the displayed response curves.

A demonstration of how to implement non-linear response curves

Now here is the same demo but this time using a TouchPad. Click on the touchpad to engage. In this demo horizontal movement controls the standard curves and vertical the inverted.

How to implement non-linear response curves with a touchpad

The source for these demos and the Ranged Number class can be found here: Ranged Number ZIP

12
Nov
09

### FOTB09 Full Presentation Video Now Available

The full video of my presentation at Flash on the Beach is now available. “How to build a game in 3 minutes” became “How to build 3 games in 3 minutes” (just showing off).

Flash on the Beach 09: 3 Games in 3 Minutes

On the back of this presentation I have now been invited to do a full hour presentation at FOTB2010, which is great news!!

I am still (slowly – too many projects on the go at once) building the Games Sketchpad and will post the app and some source as soon as it is ready. It’s already great fun to play with – just needs a bit more functionality.

29
Sep
09

### Flash on the Beach (Part #1): Elevator Pitch… AS3 Genie Effect Transition.

My ‘build a game in three minutes’ session at this year’s excellent Flash on the Beach somehow morphed into building three games in three minutes.

My initial thinking was to code on the fly and put together something simple – I wanted physics and the ability to render a 3D version. It only took a couple of experiments to realise that trying to write AND compile in a strict 3 minutes would be near impossible. I needed some assets and wanted to produce these in the allotted time too.

While cogitating the pitch, I had a lot of game commissions and ideas come through my desk. I clicked that a Game Scratchpad would be a really handy app. Something that I could sketch out a game with – to demonstrate an idea during a brainstorm – at the speed of thought.

More on the Game Sketchpad in Part#2. See the last two minutes of the pitch here (not sure what happened to the first minute):

In the meantime, I got asked by quite a few about the transition effect I used on my slides. To save time I did all of my presentation from within a swf. I wanted a fun quirky transition. The Genie (Ginny) effect is newish – I’d spotted it on wonderfl.net by Clockmaker (inspired by Fladdict). So I grabbed the method and adapted it to allow me to fire it off from a given point – connecting relevant sprites (humorous and tasteless in good measure).

I have packaged the Genie effect here as a Class, with example implementation.

//Usage
import com.swingpants.effect.GenieBmd
var gb:GenieBmd=new GenieBmd(400,300,20)// image width, height, number of segments
gb.startGenie(bmd) // Bitmapdata
gb.fireAtPoint(50,100,3) //x, y, speed (in secs)

Swingpant's AS3 Genie Effect implementation

In part#2 I will explain how the Game Sketchpad works, the component parts, the swf and some source code.

Genie Effect (zip): source

19
Sep
09

### Wonderfl Checkmate Challenge: Cityscape 3D

Wonderfl is a service that allows for AS3 coding and swfs to be built online. The site has been running a series of challenges called the Checkmate Challenge. Each month an AS3 superstar sets a challenge each for professionals and amateurs.

Takayuki Fukatsu set a professional challenge to develop an interesting application that used dot patterns to create a visual effect.

I decided to build a generated 3D Cityscape – using the dot patterns to give me a limited variation of windows.

I needed an algorithm that would randomly create the design for a skyscrapers. The building block shapes I decided on were a cube, a cylinder and a tapered cylinder. Each skyscraper was given a maximum number of iterations and a target height. The base was built and each subsequent iteration was at most 70% of the size of the level below it.

3D engine Papervision was used, my choice was restricted here as I was building within Wonderfl.net, which doesn’t have Away3D (my usual weapon of choice) installed. PV3D was fine and did the job well.

The city was built on a grid system, this means I will be able to add roads, traffic, etc at a later date. It employs a very random tower creation system, maybe a Fibonacci sequence pseudo random system would give more useful and recreatable results.

The 3D Cityscape was awarded Knight status and elicited the comment: “The texture of 3D city composed of a monochrome dot was minimal and very fantastic.”

Cityscape 3D

Sources and swf available here.

04
Sep
09

### Swingpants presenting at Flash on the Beach 09

I’m honoured to be doing a presentation at this year’s Flash on the Beach. My pres is titled “How to make a game in three minutes“, and will be part of the Elevator Pitch: 3 Minute Wonders session. Why is it called an Elevator Pitch? This is based on the maximum amount of time you’d have in a lift (elevator) to explain an idea to someone. 20 Flash luminaries (new and old) will be quick fire presenting cool ideas, concepts, code, design or latest work. It’s sure to be a (data) blast.

In “How to make a game in three minutes” I will be making a game on the fly. This will incorporate a few topics I’ve been interested in and using heavily, such as colour mapping, collision detection, physics and more. Only three minutes? Yeah, got to prep a few libraries which hopefully I can get ready in time. Certainly I won’t have any time to make mistakes. I’ll post the content here as soon as it is available.

FOTB is a great event. The best conference in the calendar, which every year has the world’s best Flash/Actionscript/Design talent: Mario Klingemann, Andre Michelle, Carlos Ulloa, Joa Ebert, Grant Skinner, Ralph Hauwert, Seb Lee Delise +++ as well as over 1200 delegates.

Flash on the Beach Speaker

30
Apr
09

Quick post to describe how to apply a gradient mask to a display object in AS3 (& AS2).

#2 Put the object to be masked on the stage.
#3 Set both the mask and the ‘object to be masked’ to cacheAsBitmap
#4 Apply the mask to the object

In #AS3

In #AS2

It really is as simple as this.
Note to designers: Gradient masks can’t obviously be done directly from the IDE (see below), but these three lines can be placed on the timeline if so desired.

To put a gradient mask on dynamic text you will need to place the text within a container (movieclip/sprite) and mask that.

The object to be masked can also contain animation, text or video though this will require a bit more processor as the bitmap will need to redraw on each frame. Often this is well worth it as the effect can be great.

There is a way of achieving this same effect with no code at all and here it is:

#2 Put the object to be masked on the stage.
#3 Put both of these items into a movieclip/sprite (the container) making sure the mask is on a layer above the object
#4 Give the mask a blend mode of ‘Alpha’
#5 Give the ‘container’ a blend mode of ‘Layer’

And there you have it. Gradient masking achieved with blendModes and absolutely no code.

I used each method to mask an embedded video – then placed an instance on the display list and ran at varying frame rates.
Initially there was negligible difference between the code and blend mask methods. I ramped up the FPS to 120 and put four instances of the video on screen. With this set up the code method (cacheAsBitmap) was up to 4% faster than the blendMode Mask method.

Conclusion: The code method is faster but very marginally. If you are desperate for a bit of extra juice go with code.

16
Mar
09

### Collision Detection and Bounce Calculation using Colour Maps (part 1)

Here is a method I developed for a game I produced last year. I had three days, and a top down ball bouncing game with multiple levels to render. Initially I thought I’d use box2D, zero out the gravity, and then build the scenes as box2D models. This looked like taking far too long to create so I needed a quick fire solution. Then it dawned on me: Colour Maps (or to you chaps over the pond Color Maps).

Now Colour Maps are nothing new, but my idea adds to the technique.

Colour Mapping means you can build a map of your game scene with various colours representing the walls and objects. To test whether you have collided with an object, instead of numerous intersect calculations you can just test the colour of the pixel(s) underneath your character.

I realised that if I added a sprite graphic for my ball to the colour map using the Blend Mode ‘add’ then I could see collision. So if I make all the static scene furniture red (0xFF0000) and the ball sprite green (0x00FF00), when they overlap the intersection area becomes yellow.

Blend Mode collision detection

So how does this help? I calculated that by using getColorBounds on the intersect yellow, I can draw a line from the centre of the rectangle to the centre of the ball. This now becomes the reflection point. I can reflect the angle of bounce against this to give a very accurate result.

Calculate the angle of reflection

OK. So the method will bounce from a partial intersection – but this means that we are calculating the bounce from a ball embedded within the border/scene furniture. I have improved this by calculating the ball path using a recursive method. The function backtracks to where the edge of the ball touches the furniture and then recalculates the path for the remaining distance to be travelled on the current iteration.

The Colour Map Bounce system in action

Here is a link to a quick demo of the method in action. Demo

Source and example usage is to follow in part 2.