Adding Event Listeners to Buttons - actionscript-3

I am new to Actionscript and I am creating a simple addition game where the player will click on numbers 1 through 9 on the bottom of the screen to solve an addition problem. Should I create individual buttons or movieclips on the bottom?
How do I add event listeners to the buttons/movieclips to be able to tell if the player clicked the second button as opposed to other buttons on the screen. Thank you!

Pretty similar to Ronnie's solution (I was almost finished this so had to post) and it is tested:
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
import flash.text.TextFormat;
var buttonCount = 9;
var buttonSize = 50;
var button:MovieClip;
var label:TextField;
for (var i:int = 0; i < buttonCount; i ++)
{
// Create a new MovieClip
button = new MovieClip();
// We'll use this in the event handler to identify which button was clicked
button.id = i + 1;
// Draw the background in the graphics prop of the MovieClip
button.graphics.beginFill(0x00ff00, 1);
button.graphics.drawRect(0, 0, buttonSize, buttonSize);
// Add event listener
button.addEventListener(MouseEvent.CLICK, this.clickHandler);
// Position the button
button.x = i * (buttonSize + 20); // Add some spacing
button.y = stage.stageHeight - buttonSize - 10;
// Add the button to the stage
addChild(button);
// Create the label for the button
label = new TextField();
label.text = button.id.toString();
label.selectable = false;
label.multiline = false;
label.autoSize = TextFieldAutoSize.LEFT;
label.setTextFormat(new TextFormat('Arial', 12, 0, true));
// Position the label in the centre of the button
label.x = (buttonSize - label.width) / 2;
label.y = (buttonSize - label.height) / 2;
// Add the label to the button MovieClip
button.addChild(label);
}
function clickHandler(event:MouseEvent):void
{
trace("Button clicked:", event.currentTarget.id);
}

What I would do is make a single movie clip with a text field in it. For example, I have a movie clip (with a linkage name of NumClip) and a dynamic text field inside called numText (Be sure to embed numerals or whatever other characters you need). Then a simple for loop should do the trick.
var maxNum:Number = 9;
for (var i:int = 1; i <= maxNum; i++)
{
var clip:NumClip = new NumClip();
clip.x = i * (clip.width + 5);
clip.y = 50;
clip.id = i;
clip.numText.text = String(i);
clip.addEventListener(MouseEvent.CLICK, numClick);
addChild(clip);
}
function numClick(e:MouseEvent):void
{
trace("You clicked number " + e.currentTarget.id);
}
I haven't tested this code, but it looks good to me and should do the trick

Related

AS3 Show and hide movieclip/image when button/mc is clicked

I want to make something like this http://www.bakedbymelissa.com/checkout/CustomizerCreator.aspx
for now I have squares(square1,square2,square3,square4) as cupcakes and circles(circle1,circle2,circle3,circle4) as the buttons. If I click circle1, square1 should appear and so on. The AS has a separate layer and the shapes are all in one layer. I placed the squares on top of each other but the problem is, when I click the buttons, the square shows up but it can't really be seen cuz it's beneath the square on top of it. How do you do it so that the corresponding square appears and the previous square that appeared, disappears? Any alternatives that you know that does the trick is fine.
my stage looks like this
AS3:
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;
var fadeIn:Tween;
var thisCircle:MovieClip;
var thisSquare:MovieClip;
var circles:Array = new Array(circle1,circle2,circle3,circle4);
var squares:Array = new Array(square1,square2,square3,square4);
for(var i:Number = 0; i < circles.length; i++)
{
thisCircle = circles[i];
thisCircle.buttonMode = true;
thisCircle.id = i;
thisCircle.addEventListener(MouseEvent.CLICK, doFadeIn);
thisSquare = squares[i];
thisSquare.alpha = 0;
}
function doFadeIn(e:MouseEvent):void
{
e.currentTarget.mouseEnabled = false;
trace(e.currentTarget.name + " is disabled while " + squares[e.currentTarget.id].name + " tweens in.");
fadeIn = new Tween(squares[e.currentTarget.id],"alpha",None.easeNone,0,1,2.5,true);
fadeIn.addEventListener(TweenEvent.MOTION_FINISH,enableButton(e.currentTarget));
}
function enableButton(thisButton:Object):Function
{
return function(e:TweenEvent):void
{
thisButton.mouseEnabled = true;
trace(e.target.obj.name + " has finished fading in, "+ thisButton.name + " is now enabled again.");
};
}
//credits to fruitbeard for the code.
I think that in your code you have forgot to fade out the current square and then fade in the new one.
Take a look on this code :
// to indicate the index of current active circle/square
var current:int = 0;
var fadeIn:Tween, fadeOut:Tween;
var thisCircle:MovieClip;
var thisSquare:MovieClip;
var circles:Array = new Array(circle1, circle2, circle3, circle4);
var squares:Array = new Array(square1, square2, square3, square4);
for(var i:Number = 0; i < circles.length; i++)
{
thisCircle = circles[i];
thisCircle.buttonMode = true;
thisCircle.id = i;
thisCircle.addEventListener(MouseEvent.CLICK, doFadeIn);
// keep the first square as visible
if(i != current){
thisSquare = squares[i];
thisSquare.alpha = 0;
}
}
function doFadeIn(e:MouseEvent):void
{
// if our button is the active one, exit
if(current == e.currentTarget.id) return;
// fade out current square
fadeOut = new Tween(squares[current], "alpha", None.easeNone, 1, 0, 2.5, true);
// fade in the new active square
fadeIn = new Tween(squares[e.currentTarget.id], "alpha", None.easeNone, 0, 1, 2.5, true);
current = e.currentTarget.id;
}
You can see this code working here.
I hope this can help you.

How to add a keyboard navigation to a Flash AS3 based app?

I would like to make my Flash AS3 based app more accessible with a keyboard navigation.
What's the best way to add to every MovieClip with a MouseEvent.CLICK the ability to get selected through the TAB and clicked/fired through ENTER?
Some basic example of my code:
nav.btna.addEventListener(MouseEvent.CLICK, openSection);
dialog.btnx.addEventListener(MouseEvent.CLICK, closeDialog);
function openSection(event:Event=null):void
{
trace("nav.btna")
}
function closeDialog(event:Event=null):void
{
trace("dialog.btnx")
}
I remember that there was a AS3 function that enabled that every MovieClip with a MouseEvent could be fire through ENTER if the MovieClip was selected with TAB. I can't remeber the function though.
I think the problem may be that you are attempting this with a MovieClip instead of a button (Button or SimpleButton).
I made a simple test by creating buttons instead of MovieClips in my library and this worked as expected:
// I have 4 buttons (button1, button2, etc) on the stage
for(var i:int = 1; i <= 4; i++)
{
var mc = getChildByName("button" + (i+1));
mc.tabIndex = i;
mc.addEventListener(MouseEvent.CLICK, onClicked);
}
function onClicked(e:MouseEvent):void
{
trace(e.currentTarget + " clicked");
}
stage.focus = stage;
I initially ran this test with MovieClip instances, and while they would show that the tab was working (a yellow border shows up), the MouseEvent.CLICK was never firing. Once I switched to actual buttons (SimpleButton in this case), it worked with both the Enter and Space keys.
EDIT:
To answer the question posed in the comments, this is a quick-and-dirty way to "convert" MovieClips to SimpleButtons at runtime:
// I have 4 MovieClips (button1, button2, etc) on the stage
for(var i:int = 1; i <= 4; i++)
{
var mc:MovieClip = getChildByName("button" + i) as MovieClip;
var button:SimpleButton = convertMovieClipToButton(mc);
button.tabIndex = i;
button.addEventListener(MouseEvent.CLICK, onClicked);
}
function convertMovieClipToButton(mc:MovieClip):SimpleButton
{
var className:Class = getDefinitionByName(getQualifiedClassName(mc)) as Class;
var button:SimpleButton = new SimpleButton(new className(), new className(), new className(), new className());
button.name = mc.name;
button.x = mc.x;
button.y = mc.y;
mc.parent.addChildAt(button, getChildIndex(mc));
mc.parent.removeChild(mc);
return button;
}

Actionscript, set objects invisible

This is a script for when i click an object, it opens a small book with some page flip effect.
I'm done with almost everything but i want that when i click in a back button everything desapears and i go back to only seeing the original object. It is not working because its only deleting one of the pages! I tried doing an array but it didnt work either and Im not very good with arrays too. Can anyone help?
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.Sprite;
import flash.display.Loader;
var cont : DisplayObject;
var cont2 : DisplayObject;
var imgLoader : Loader;
//loads pages
for (var i:int=0; i<=4; i++){
imgLoader = new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.INIT, onLoadJPEG);
imgLoader.load(new URLRequest(""+i+".png"));
}
var imgLoader2 : Loader;
//loads back button
imgLoader2 = new Loader();
imgLoader2.contentLoaderInfo.addEventListener(Event.INIT, onLoadSketch);
imgLoader2.load(new URLRequest("voltaatrassketchbook.png"));
function onLoadJPEG (e : Event) : void {
cont = e.target.loader;
cont.x =250;
cont.y =50;
cont.width = (445-100)/2;
cont.height = (604-100)/2;
addChild(cont);
cont.addEventListener(MouseEvent.MOUSE_UP, FlipPage);
}
function onLoadSketch (e : Event) : void {
cont2 = e.target.loader;
cont2.x =450;
cont2.y =300;
cont2.width = 181/2;
cont2.height = 127/2;
addChild(cont2);
cont2.addEventListener(MouseEvent.MOUSE_UP, volta);
}
function FlipPage(e:MouseEvent):void{
setChildIndex(DisplayObject(e.currentTarget), this.numChildren - 1);
if (e.currentTarget.rotationY == 0) {
var myTween:Tween = new Tween(e.currentTarget, "rotationY",
Regular.easeInOut,0, 180, 1, true);
}
if (e.currentTarget.rotationY == 180) {
var myTween:Tween = new Tween(e.currentTarget, "rotationY",
Regular.easeInOut, 180, 0, 1, true);
}
}
//function to go back
function volta (e: MouseEvent): void {
gotoAndStop(1);
cont.visible=false;
cont2.visible=false;
}
Option 1
You are right that you could use an array. Put this at the top of your code, before you start loading the pages:
var pages:Array = [];
Then put this as the final line inside onLoadJPEG()
pages.push(cont);
That will add each image to the array when it is loaded.
Then in volta() you can loop through the array and make each image invisible
for(var i:int = 0; i < pages.length; i++) {
DisplayObject(pages[i]).visible = false;
}
Option 2
Another approach would be to add all the images to a container Sprite and then all you would have to do is make the container Sprite invisible.
Add this to the top of your code before you load the pages :
var pages:Sprite = new Sprite();
addChild(pages);
Then in onLoadJPEG() add cont as a child of the container
pages.addChild(cont);
Then in volta() :
pages.visible = false;
If you use this approach, don't forget to call setChildIndex() on the container inside of FlipPage() :
pages.setChildIndex(DisplayObject(e.currentTarget), this.numChildren - 1);

Relative coordinate issue in AS3

I've edited the following code in order to let those green rectangles to follow my cursor which is customized by a small rectangle. But I've encountered several problems:
Although I haven't defined any coordinate in the separate class, but the size is abviously wrong in the stage when publish with only half size for the cursor coordinate.
The reset button cannot be activated, although I've tested well in the other code.
Here is the work I've published: http://neowudesign.com/hwu_ex04.html
The code on timeline
//hw//Creating a new cursor
newcursor.startDrag ("true");
Mouse.hide();
//hw//Creating a holder to hold the butterfly objects
var mothHolder = new Sprite();
addChild(mothHolder);
//hw//Creating seven moths at the beginning
makeMoths(7);
//hw//creating a function which can generate limited numbers of moths.
function makeMoths(MothsNumber:Number)
{
for (var i = 0; i < MothsNumber; i++)
{
newMoth = new Moth();
mothHolder.addChild(newMoth);
}
}
//hw//Set the reset button at the top for clicking, but it's failed to work;
//hw//Set the cursor back to the default one, and remove the custom one when hovering;
mothHolder.setChildIndex(reset,mothHolder.numChildren);
reset.addEventListener(MouseEvent.MOUSE_OVER, cursorchange);
function cursorchange(event:MouseEvent):void
{
Mouse.show();
newcursor.visible = false;
trace("alert!!");
}
//hw//creating a function of reset
reset.addEventListener(MouseEvent.CLICK, resetClick, false, 0, true);
function resetClick(evt:MouseEvent):void
{
removeChild(mothHolder);
mothHolder = new MovieClip();
addChild(mothHolder);
var numMoths:Number = Math.round(Math.random() * 6) + 1;
trace("Moths Numeber: "+ numMoths);
makeButterflies(numButterflies);
}
//hw//when the cursor leave the reset region, it turns back to the customized one
reset.addEventListener(MouseEvent.MOUSE_OUT, fl_MouseOutHandler);
function fl_MouseOutHandler(event:MouseEvent):void
{
removeEventListener(MouseEvent.MOUSE_OVER, cursorchange);
Mouse.hide();
newcursor.visible = true;
}
And the code for class "Moth" separately named "angle.as"
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.Point;
public class angle extends MovieClip {
var speed:Number = 8;
function angle() {
//letting every moth follow the moving of the cursor
addEventListener(Event.ENTER_FRAME,mothMove);
function mothMove(myEvent:Event) {
trace(mouseX);
trace(mouseY);
var angle:Number = Math.atan2(mouseY - y, mouseX - x);
x += Math.cos( angle ) * speed;
y += Math.sin( angle ) * speed;
}
}
}
}

Actionscript3: Countdown number of ducks

Clouds,
ducks,
score
display
and
waves
should
each
have
a
class
to
govern
their
movement
and
behavior.
When
ducks
are
clicked
on
they
are
“shot”
and
the
duck
is
removed
from
the
array
as
well
as
from
the
stage
(use
arrayName.splice()
for
this).
The
score
display
should
count
down
as
this
occurs.
The
number
of
ducks
left
should
be
a
property
within
the
Score
Display’s
class
and
adjusted
by
Main
when
the
ducks
are
shot.
When
all
the
ducks
are
“shot”
the
game
should
animate
the
“you
win”
message.
This
can
be
done
by
adding
and
removing
event
listeners
that
associate
an
ENTER
FRAME
event
with
an
animating
function.
(This
is
worth
only,
so
leave
it
for
last).
When
the
ducks
are
“shot”
the
waves
and
clouds
should
also
be
removed
from
view
AND
from
their
respective
arrays.
Game
should
reset
after
player
has
won
or
lost
many
times.
(not
just
once)
I have most of this done, I'm just having trouble with the scoreboard. Any tips on how to reset everything, and code the you win sign would help too.
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
[SWF(width="800", height="600", backgroundColor="#E6FCFF")]
public class Main extends Sprite
{
private var _sittingDucks:Array = []; //always set your arrays with [] at the top
public var _scoreDisplay:TextField
public function Main()
{
//adding the background, and positioning it
var background:Background = new Background();
this.addChild(background);
background.x = 30;
background.y = 100;
for(var i:uint = 0; i < 5; i++)
{
//adding the first cloud, and positioning it
var clouds:Clouds = new Clouds();
this.addChild(clouds);
clouds.x = 130 + Math.random() * 600; //130 to 730
clouds.y = 230;
clouds.speedX = Math.random() * 3;
clouds.width = clouds.height = 200 * Math.random()//randomly changes the clouds demensions
}
var waves:Waves = new Waves();
this.addChild(waves);
waves.x = 0;
waves.y = 510;
waves.speedX = Math.random() * 3;
for(var j:uint = 0; j < 8; j++)
{
var ducks:Ducks = new Ducks();
this.addChild(ducks);
ducks.x = 100 + j * 100;
ducks.y = 475;
_sittingDucks.push(ducks);
ducks.addEventListener(MouseEvent.CLICK, ducksDestroy);
}
var waves2:Waves = new Waves();
this.addChild(waves2);
waves2.x = 0;
waves2.y = 520;
waves2.speedX = Math.random() * 3;
var setting:ForeGround = new ForeGround();
this.addChild(setting);
setting.x = 0;
setting.y = 50;
setting.width = 920;
var board:ScoreDisplay = new ScoreDisplay();
this.addChild(board);
board.x = 570;
board.y = 35;
}
private function ducksDestroy(event:MouseEvent):void
{
//store the crow we clicked on in a new array
var clickedDuck:Ducks = Ducks(event.currentTarget);
//remove it from the crows array
//find the address of the crow we are removing
var index:uint = _sittingDucks.indexOf(clickedDuck);
//remove it from the array with splice
_sittingDucks.splice(index, 1);
//remove it from my document's display list
this.removeChild(clickedDuck);
}
}
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import ScoreDisplayBase; // always import the classes you are using
public class ScoreDisplay extends ScoreDisplayBase
{
private var txt:TextField; // where is it initialized?
private var score:uint = 0;
public function ScoreDisplay()
{
super(); // do you init txt here?
}
public function scoreUpdate():void
{
score += 10; // ok, so I suppose that your score does not represent the remaining ducks as you said, just only a score
txt.text = score.toString();
}
}
Aaaalrighty:
You do want to create the TextField txt in ScoreDisplay's constructor. Instantiate it, set its text to initial score (0), and addChild(txt).
In order to set the score later, we'll need a way to reference the display.
//you want a reference to the ScoreDisplay, not this
public var _scoreDisplay:TextField //no
public var _scoreDisplay:ScoreDisplay //yes
and when you create it in the Main constructor, we need to keep a reference.
_scoreDisplay = :ScoreDisplay = new ScoreDisplay();
this.addChild(_scoreDisplay );
_scoreDisplay .x = 570;
_scoreDisplay .y = 35;
If you want to be able to reset the game, I would recommend taking the duck creation and placing it in a method outside the Main class' constructor. You should also create a 'reset' function that sets the score (and the display) to 0 in ScoreDisplay.
private function spawnDucks() {
for(var j:uint = 0; j < 8; j++)
{
var ducks:Ducks = new Ducks();
this.addChild(ducks);
ducks.x = 100 + j * 100;
ducks.y = 475;
_sittingDucks.push(ducks);
ducks.addEventListener(MouseEvent.CLICK, ducksDestroy);
}
}
and then you call it in the constructor, and can call it again when you need to reset the game.
ducksDestroy(event:MouseEvent) is going to be where you want to recalculate the score, check if you've won, show a message, and reset the game. You'll need some kind of popup to display, here is a decent one if you don't know where to get started at with that.
private function ducksDestroy(event:MouseEvent):void
{
//store the crow we clicked on in a new array
var clickedDuck:Ducks = Ducks(event.currentTarget);
//remove it from the crows array
//find the address of the crow we are removing
var index:uint = _sittingDucks.indexOf(clickedDuck);
//remove it from the array with splice
_sittingDucks.splice(index, 1);
//remove it from my document's display list
this.removeChild(clickedDuck);
//update the score
_scoreDisplay.scoreUpdate();
//Check if all the ducks are gone
if (_sittingDucks.length == 0) {
//All the ducks are dead, we've won the game!
//create some kind of popup to display.
//add it to the screen, have some form
//of button (or a timer) take it away
//whatever takes the popup away, have it call 'reset'
}
}
private function reset():void
{
//write a reset method to clear the score
_scoreDisplay.reset();
//create some ducks and you're ready to go!
spawnDucks();
}