Creating an Interactive Animated Background With Flex and Actionscript

Written by:  • Edited by: Linda Richter
Updated Nov 6, 2009

In part 3 of the series we finally got to draw some graphics to the screen. In part 4 we will take this one step further and make the game object interactive. We will also create a background level that the player can fly over.

The majority of Flash games tend to be quite simple in nature. They are 5 – 10 minute distractions that are played during lunch, or when the boss isn’t looking. This simplicity is also reflected in the typical control scheme employed by Flash games: mouse input with a single left click. It’s intuitive (someone who will only devote a few minutes of their time to playing the game isn’t going to want to read a help page with a complicated control scheme), and Flash doesn’t let you (easily) work with the right mouse button anyway.

Thankfully our top down shooter style of game play lends itself nicely to this simple control scheme. The player will simply move the mouse around the screen to move the players ship and click the left mouse button to fire weapons. But before we can create a game object that represents the players ship we first need a way of detecting where the mouse has been moved to, and when the mouse button has been clicked. Lets look at what changes have to be made to the main.mxml file to accommodate this.

Detecting Mouse Movement

<?xml version="1.0" encoding="utf-8"?>

<mx:Application

xmlns:mx="http://www.adobe.com/2006/mxml"

layout="absolute"

width="600"

height="400"

frameRate="100"

creationComplete="creationComplete()"

enterFrame="enterFrame(event)"

click="click(event)"

mouseDown="mouseDown(event)"

mouseUp="mouseUp(event)"

mouseMove="mouseMove(event)"

currentState="MainMenu">

<mx:states>

<mx:State

name="Game"

enterState="enterGame(event)"

exitState="exitGame(event)">

</mx:State>

<mx:State name="MainMenu">

<mx:AddChild relativeTo="{myCanvas}" position="lastChild">

<mx:Button x="525" y="368" label="Start" id="btnStart" click="startGameClicked(event)"/>

</mx:AddChild>

</mx:State>

</mx:states>

<mx:Canvas x="0" y="0" width="100%" height="100%" id="myCanvas"/>

<mx:Script>

<![CDATA[

protected var inGame:Boolean = false;

public function creationComplete():void

{

}

public function enterFrame(event:Event):void

{

if (inGame)

{

GameObjectManager.Instance.enterFrame();

myCanvas.graphics.clear();

myCanvas.graphics.beginBitmapFill(GameObjectManager.Instance.backBuffer, null, false, false);

myCanvas.graphics.drawRect(0, 0, this.width, this.height);

myCanvas.graphics.endFill();

}

}

private function click(event:MouseEvent):void

{

GameObjectManager.Instance.click(event);

}

private function mouseDown(event:MouseEvent):void

{

GameObjectManager.Instance.mouseDown(event);

}

private function mouseUp(event:MouseEvent):void

{

GameObjectManager.Instance.mouseUp(event);

}

private function mouseMove(event:MouseEvent):void

{

GameObjectManager.Instance.mouseMove(event);

}

protected function startGameClicked(event:Event):void

{

currentState = "Game"

}

protected function enterGame(event:Event):void

{

Mouse.hide();

GameObjectManager.Instance.startup();

Level.Instance.startup();

inGame = true;

}

protected function exitGame(event:Event):void

{

Mouse.show();

Level.Instance.shutdown();

GameObjectManager.Instance.shutdown();

inGame = false;

}

]]>

</mx:Script>

</mx:Application>

We have added functions to listen to 4 new events: mouseMove, click, mouseDown and mouseUp. MouseMove is, as you would expect, called when the mouse has been moved. It allows us to monitor the position of the mouse cursor over the flash player window. Similarly click monitors when the mouse button has been clicked (i.e. pressed and released). When the mouse button is pressed mouseDown is fired, and when it is released mouseUp is fired. We need the ability to monitor the mouseDown and mouseUp events individually (as opposed to the click event which fired after the mouse has been pressed and then released) because eventually we want the player to fire weapons when the mouse button is pressed and stop when it is released.

The four new functions have the same name as the event as their respective event, and simply pass the message along to the GameObjectManager.

Showing page 1 of 5

Comments

Showing all 24 comments
 
Jibb Jun 27, 2010 12:35 PM
Thanks Greg
Thanks Greg, but I did try that and was unable to get it working. I may have put it in the wrong place or something, but eventually I gave up (weeks ago, I believe) and found a tutorial on using as little mxml as possible so I could stay where I was comfortable: in AS3.

This tutorial continued to be helpful anyway as a reference, even if I was no longer going through it step by step.

Jibb
Greg Cable Jun 26, 2010 2:04 PM
MouseEvent Error - to Jibb
Jibb had an issue:
'MouseEvent causing error
In main.mxml I'm getting an "Error: Type was not found or was not a compile-time constant: MouseEvent".'

First time doing anything with Flex4 but with most languages this means you are missing an include. Sure enough after looking through the API documentation I found the following worked to resolve the issues:

import flash.events.*;

Perhaps it is a version issue? I hope this helps you Jibb :)
Jibb Mar 30, 2010 12:42 AM
MouseEvent causing error
In main.mxml I'm getting an "Error: Type was not found or was not a compile-time constant: MouseEvent".

The same happens if I replace my main.mxml with your demo source code (I thought I'd try it, even though as far as I could tell the only differences where in whitespace).

Sorry, but I'm very new to this.

Any ideas why this is happening?
Chandra Mar 28, 2010 12:35 AM
Awesome Tutorial
Thx a lot Mat, this tutorial is awesome and really help a beginner like me :).

I think you miss to modify ResourceManager.as in the tutorial, to add SmallIsland, BigIsland, and VolcanoIsland. Good luck.
LP Jan 27, 2010 4:18 AM
RE: Creating an Interactive Animated Background With Flex and Actionscript
Hi,
I get the following error under Level.as

1119: Access of possibly undefined property SmallIslandGraphics through a reference with static type Class.


Please help
JC Jan 23, 2010 5:29 PM
Mouse Up outside the main area
Hi, I'm a c++ game prog and I just started looking at as3 programming. I used your example to create my own stuff. I have a problem with the mouse when trying to do a drag and drop feature. If the button is released outside the game area it isn't detected. Is there anyway to solve this in your tutorial?

thanks

JC
cabs Jan 11, 2010 9:49 PM
Mouse Events
Thank you for your nice tutorial.
I would just like to ask on how would you enable mouse events for individual objects? I tried identifying them by mouse location but since i have multiple objects in isometric view, it was quite difficult.
Segato Dec 7, 2009 6:36 PM
KeyboardEvent II
Thanks for the answer, but the problem is i cant conect the Player class with the keyboard events.

I already know the diferents codes for keycodes, but i can make the ship move with arrow keys
Matthew Casperson Dec 7, 2009 6:24 PM
RE: Creating an Interactive Animated Background With Flex and Actionscript
You can find a simple Flex demo that responds to keyboard input at http://www.brighthub.com/hubfolio/matthew-casperson/blog/archive/2009/09/13/keycode-in-flash-flex.aspx

The code used there would be the same as what would be needed here in this game.
Segato Dec 6, 2009 11:24 PM
Same game, with KeyBoardsEvents??
First of all, thanks for this tutorial, i learned a lot from this. But my question is how to move the ship with the keyboard.

I did the same steps as mouseEvents but nothing happen, the ship dont move.

I added the events in:
main
gameObject
gameObjectManager

What am i missing??

Thanks for your time
Diogenes Dec 4, 2009 7:42 AM
not worked
I'm sorry , but the objects now are not appearing on screen
Matthew Casperson Dec 2, 2009 4:59 PM
RE: Creating an Interactive Animated Background With Flex and Actionscript
The ships move down the screen by modifying the y variable of the position in the enterFrame function like:

position.y += scrollRate * dt;

To move them in different directions, you just need to add some new logic to the enterFrame function to modify the position variable in a different way.
Diógenes Dec 2, 2009 12:27 PM
changing direction
how can I change the direction of objects? both ships many other objects?
Matthew Casperson Nov 8, 2009 9:24 PM
RE: Creating an Interactive Animated Background With Flex and Actionscript
No. Once an object is removed from the system it is returned to the pool. Which object is pulled from the pool for a new object does not matter.

Remember that the pools are specific to a class, so if you are getting an unused Enemy, you are getting that object from a pool that holds only Enemy objects.
Konstantin Nov 8, 2009 4:12 AM
Still don'd understand
Does it matters what unsused item we get in result?
Matthew Casperson Nov 7, 2009 6:10 PM
RE: Creating an Interactive Animated Background With Flex and Actionscript
Aryadi Nov 7, 2009 1:47 PM
Keboard input?
How do you do keyboard input btw?
Matthew Casperson Oct 26, 2009 5:52 AM
RE: Creating an Interactive Animated Background With Flex and Actionscript
It will return an object where the inuse property is not true (i.e. the object has been shutdown). The idea is to keep the objects created during the level available for reuse instead of creating new objects and then using the garbage collector to clean them up.
Konstantin Oct 26, 2009 5:44 AM
Can't understand
Very helpful tutorial. Great job. But I can't understand this part:

public function get ItemFromPool():GameObject
{
for each (var item:GameObject in pool)
{
if (!item.inuse)
return item;
}
var newItem:GameObject = newObject();
pool.addItem(newItem);
return newItem;
}

What item does we get in result? Any unused item or something particular?
John Sep 16, 2009 1:01 PM
MathUtils.as code
Below is the MathUtils class I created when testing this example out. I salute you Matthew Casperson on a most excellent ActionScript 3 game tutorial!

Simply create a new final class called MathUtils with the static function randomInteger.

Here's the code guys:

package
{
public final class MathUtils
{
public static function randomInteger(low:Number=NaN, high:Number=NaN):Number
{
var low:Number = low;
var high:Number = high;

if(isNaN(low))
{
throw new Error("low must be defined");
}
if(isNaN(high))
{
throw new Error("high must be defined");
}

return Math.round(Math.random() * (high - low)) + low;
}
}
}
Matthew Casperson Jul 21, 2009 7:47 PM
Source Code
The source code downloads often includes classes and functions that aren't specifically covered by the article itself (like small helper functions in the MathUtils class).
Matthias Mueller Jul 21, 2009 9:59 AM
RE: Error in part 4
hi,

just create your own MathUtils class and insert a methods like:

public function randomInteger(begin : int, end : int) : int {
return Math.round(Math.floor(start +(Math.random() * (end - start)));
}

Sorry but i cannot test it yet, maybe you got some Type errors and you have to cast between the diffret types.

@ Matthew:
Very nice work, i'll have a look on it at home :D
Alan Jun 26, 2009 12:40 PM
Error with tutorial 4
Hi, Ive been using your tutorials so far and they have been quite helpful in learning how to use Flex but when I try and run tutorial 4 it gives me the following error Access of undefined property MathUtils. I just wanted to know where this is defined, is it similar to the Math function? Thanks, Alan
Tom Clark Jun 24, 2009 4:57 AM
Errors with tutorial 4
Hi,

Your tutorials have been very helpful so far. Thanks for writing them.

When I try to run the program from tutorial 4 (Flash Game Development with Flex and Actionscript - User Input and an Animated Background) I get the following errors:

1. Type was not found or was not a compile-time constant: BackgroundLevelElement. Level.as line 56
2. Access of undefined property BackgroundLevelElement. Level.as line 56
3. Access of undefined property BackgroundLevelElement. Level.as line 56

Can you please tell me how to fix this problem?

Thanks,

Tom
 
blog comments powered by Disqus
Email to a friend