Saturday, June 30, 2012

[Action Script] Efficient ActionScript 3.0 June,2012

I use FlashDevelop 4.01 to write small ActionScript projects and have messed around with Mobile Adobe Air ActionScript 3.0 Apps. My question is for anyone who would like to answer, for them to share experience, or to help point me in a better direction. Here is a small code example of a Pong type ball bouncing around a 500 x 500 px screen.

Main.as -
Code: package
{
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.display.StageScaleMode;
        import flash.display.StageAlign;
       
        [SWF(width="500", 
                height="500",
                frameRate="30", 
                backgroundColor="#000000", 
                pageTitle="AdvEngine - Flash Version 1.0")]
        public class Main extends Sprite
        {
                public static const WIDTH:uint = 500;
                public static const HEIGHT:uint = 500;
               
                private var ball:Ball = new Ball();
               
                public function Main():void
                {
                        addEventListener(Event.ADDED_TO_STAGE, init);
                        addEventListener(Event.ENTER_FRAME, update);
                        addChild( ball );
                }
               
                private function init(e:Event = null):void
                {
                        removeEventListener(Event.ADDED_TO_STAGE, init);
                        stage.scaleMode = StageScaleMode.NO_SCALE;
                        stage.align = StageAlign.TOP_LEFT;
                }
               
                private function update(event:Event):void {
                        ball.update();
                }
               
        }
       
}
Ball.as -
Code: package
{
        import flash.geom.Point;
        import flash.display.Bitmap;
        import flash.display.BitmapData;
       
        public class Ball extends Bitmap
        {
               
                private var fp:Point        = new Point(0, 0);
                private var dx:int                = 5;
                private var dy:int                = 4;
               
                public function Ball()
                {
                        super( new BitmapData( 10, 10, false, 0xffffff ) );
                        cacheAsBitmap = true;
                }
               
                public function update():void {
                       
                        fp.x = x + dx;
                        fp.y = y + dy;
                       
                        // test horz boundaries
                        if ( fp.x < 0 ) {
                                fp.x = 0;
                                dx *= -1;
                        }else if ( Main.WIDTH < (fp.x + width) ) {
                                fp.x = Main.WIDTH - width;
                                dx *= -1;
                        }
                       
                        //test vert boundaries
                        if ( fp.y < 0 ) {
                                fp.y = 0;
                                dy *= -1;
                        }else if ( Main.HEIGHT < (fp.y + height) ) {
                                fp.y = Main.HEIGHT - height;
                                dy *= -1;
                        }
                       
                        x = fp.x;
                        y = fp.y;
                       
                }
        }

}When the movie starts up it is choppy, for maybe the first 3 seconds, then it evens out, but continues to look choppy every now and then. Changing the frame rate to 60 instead of 30 makes it move without any choppy-ness on the computer, but for some reason my phone won't allow more than 35 - 40 fps. I thought using Bitmaps and cacheAsBitmap and cacheAsBitmapMatrix would be the best options I had for hitting that frame rate each time, but it still seems choppy. I thought 30 would be more than enough for solid fps.

- Is there a way to give more initial memory to the application? Would this help?

- Is there a way to push rendering to the GPU effectively instead of CPU ( I know the application.xml file in the mobile development has a tag <renderMode> which can be changed to gpu, but this has always slowed my application to 19 - 22 fps...

- Any ideas would be awesome. Or let me know if the above code runs perfectly smooth for you.

Thanks ahead of time
Efficient ActionScript 3.0

[Action Script] Button-controlled fade June,2012

I have two keyframes containing images, and a button on the first. I would like to find out how to script that button to, when rolled over, fade to the second frame, and fade back to the first frame when the mouse is rolled off.
Button-controlled fade

[Action Script] Preloader loads too fast June,2012

Hii,

My preloader is in frame one and it has only 6 kb of data, its for a game, it loads really fast , i really would like it to show up for atleast 4-5 seconds before it goes to game play page .....

i am using the below code on the Preloader.as

//////////////////////////////
var percent:int = Math.round(e.bytesLoaded / e.bytesTotal * 100);
progressBar.width = percent / 100 * progressArea.width;
percentageText.text = percent + "%";

///////////////////////////////


can some one help me to find a way that he preloader loads a little slower and shows up for a few seconds ...


I am using the concept of loading content in frame 2 by changing the action script settings in flash cs4 ......

Thanks

Jin
Preloader loads too fast

[Action Script] Optional parameters June,2012

Hey guys, I've got the following code
Code: function menuFade(button1:TextField, button2:TextField) {
                if(fadeIn) {
                        button1.alpha = 1;
                        button2.alpha = 1;
                }
                if(!fadeIn) {
                        button1.alpha = 0.2;
                        button2.alpha = 0.2;
                }
}But I want button2 to be optional, and I can't get that to work. Can someone help me on this?
Optional parameters

[Action Script] removeChild error 2007 June,2012

First off I'd like to say I did a search on this and although there are many subjects on the matter, none really apply to mine.

My problem is this: There is an enemy on the stage(enemyTwo) in which I remove if its health meter gets below a certain point. You lower the enemy's health by hitting it with little daggers that you throw.

Everything works fine up to a point, the health bar slowly goes down and the enemy even seems to disappear when the removeChild/enemyTwo = null directives are called, however, there seems to be a small window of time where the daggers will hit an invisible version of the enemy which in turn gives me the "Error #2007: Parameter hitTestObject must be non-null" error which in turn causes other things to go awry or Id just ignore it =).


ActionScript Code: public function checkCollisionWithEnemies(bullet:MovieClip)        {                        if(enemyTwo != null)            {                if(enemyTwo.hitTestObject(bullet))                {                    enemyTwo.subObject.meter.width -= 10;                    removeChild(bullet);                                                            if(enemyTwo.subObject.meter.width < 3)                    {                                                enemyTwo.stop();                        removeChild(enemyTwo);                        enemyTwo = null;                                            }                }                                            }         }
ActionScript Code: private function onEnter(evt:Event):void        {                        y -= 10;            rotation += 20;                        MovieClip(parent).checkCollisionWithEnemies(this);                                }
Any insight would be appreciated.
removeChild error 2007

[Action Script] Way of Communication between Flash(ActionScript) and HTML.) June,2012

Hello there.!

Greetings from my side.!!

I am searching a way so as data can be shared as I/O between HTML and ActionScript code.
Is there any way to achieve this.?
Kindly, Suggest me.!
Way of Communication between Flash(ActionScript) and HTML.)

Friday, June 29, 2012

[Action Script] Hello Countdown Timer June,2012

Hello,

I was wondering if someone could break down the following code for me and make it a bit easier so that i can just set a start date / end date.

Thanks.
Code: function displayDifference()
{
    nowTime = new Date();
    hoursLeft = ((((16-nowTime.getDate())*24) + (20 - nowTime.getHours())));
        //hoursLeft = (4 - nowTime.getDate()) * 24 + (19 - nowTime.getHours());
    if (hoursLeft >= 0)
    {
        timeRemaining.text = hoursLeft + ":" + padString(59 - nowTime.getMinutes()) + ":" + padString(59 - nowTime.getSeconds()) + "";
    }
    else
    {
        timeRemaining.text = "0H 0M 0S";
    } // end else if
} // End of the functionWhat i want to do is have a Start date of a value such as July 1st
and end date of July 31st

i'm not sure how similar this is to javascript esentially i want it to be like this.

Code: /* Date Animation  starts here*/
                                $(function () {
                                var austDay = new Date();
                                var austDay = new Date("June 30, 2012 21:00:00");
                                $('#countdown').countdown({until: austDay, layout:
                                                                '<div id="days" class="numbers">{dnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="hours" class="numbers">{hnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="minutes" class="numbers">{mnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="seconds" class="numbers">{snn}</div>'+
                                                                '</div>'});
                                                                });});
Hello Countdown Timer

[Action Script] Can't copy file (SQLite) June,2012

I just wrote a simple AIR program using SQLite but can't seem to copy it (using Save As)

When the first square is pressed a number is multiplied by 1.5

When the second square is pressed the database is updated with the new number

The AIR program saves the number in the databank but the copied program doesn't

Am I going mad?





import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.data.SQLStatement;
import flash.data.SQLConnection;
import flash.filesystem.File;
import flash.events.SQLEvent;
import flash.net.Responder;
import flash.errors.SQLError;
import flash.data.SQLResult;


var ones2:Number = new Number();
ones2 = 1;

var but:Sprite = new Sprite();
but.graphics.beginFill(0x555555);
but.graphics.drawRect(0,0,40,40);
but.graphics.endFill();
but.x = 50;but.y = 50;
addChild(but);

var but2:Sprite = new Sprite();
but2.graphics.beginFill(0x555555);
but2.graphics.drawRect(0,0,40,40);
but2.graphics.endFill();
but2.x = 120;but2.y = 50;
addChild(but2);


but.addEventListener(MouseEvent.CLICK, butClick);
function butClick(event:MouseEvent):void
{
ones2 = ones2 * 1.5;
trace(ones2);
}


// ************************************************** **************************************


var connect:SQLConnection = new SQLConnection();

opendatabase();

function opendatabase():void
{
var testFile:File = File.applicationStorageDirectory.resolvePath("name File.db");
connect = new SQLConnection();
connect.addEventListener(SQLEvent.OPEN, onOpen);
connect.openAsync(testFile, SQLMode.CREATE);
}

function onOpen(SQLEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connect;
stat.text = "CREATE TABLE IF NOT EXISTS tester2 (id INTEGER PRIMARY KEY AUTOINCREMENT, one NUMERIC)";
stat.execute(-1, new Responder(onCreate, err));
}


function onCreate(SQLEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connect;
stat.text = "SELECT one FROM tester2 ORDER BY id";
stat.execute(-1, new Responder(onSelec, err));

}

function onSelec(event:SQLResult):void
{
if (event.data != null)
{
for (var i:int = 0;i<event.data.length;i++){
trace(event.data[i].one);
ones2 = event.data[i].one;
}
}
}

/* ******************
* *
* Button 2 *
* *
****************** */

but2.addEventListener(MouseEvent.CLICK, go1);
function go1(event:MouseEvent):void
{
var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = connect;
stat.text = "UPDATE tester2 SET one = "+ones2+"";
stat.execute(-1,new Responder(onCreate,err));
}






function err(error:SQLError):void
{
trace(error.message);
trace(error.details);
}
Can't copy file (SQLite)

[Action Script] Restart the timer June,2012

I know you have all seen this hundred of times but I just can't make it work :S
Its Flash 5.
ActionScript Code: x = random(8) + 1;image = "a"+x;holder.attachMovie(image, "new1",5);gotoAndPlay(2);trace(image);i = 1;function wait() { p = i++;    trace(p);    if(p == 5) {        clearInterval(myTimer);        x = random(8) + 1;        image = "a"+x;        holder.attachMovie(image, "new1",5);        trace(image);        gotoAndPlay(2);    }}myTimer = setInterval(wait, 1000);As you can see it generates the random number,put an "a" in front of it and loads image under that name from library,then waits 5 sec and do the same..the thing is that I don't know how to restart the timer so it starts from 0 again and return at the begin of the function...I hope you understand what I mean :D

Another question..I have created an application for my nokia 7230 in flash 5 but i can't fscommand it to be fullscreen,can you help me out with this one too?

Thanks :P
Restart the timer

[Action Script] how do I escape double quotes when declaring a variable. June,2012

understand I have simplified my actual code to just cover my exact need.

I need to store ""michael080900.txt""

var new_variable
text1.text = "Michael080900.txt";
new_variable = text1.text;
with the quotes

because I need to make this line look like this, but it HAS to be from a variable otherwise the rest of my code is pointless.

my_data.load("michael080900.txt");
needs to become this so that I can load it from a flashvars and it read in the text file from a dynamically generated name.

my_data.load(new_story);
how do I escape double quotes when declaring a variable.

[Action Script] help with package June,2012

Error says: "The name of package '@' does not reflect the location of this file. Please change the package definition's name inside this file, or move the file"
although the name of package is zoo, not @
Code: package zoo
{

}
help with package

[Action Script] 3D drawing - circle on a sphere June,2012

Hiya,

I was wondering if anyone could point me in the right direction. I'm looking for a way to draw a circle on 3D sphere.

I have a 3D sphere of the world, on it there's a few cities. What I want is to have these cities each have a circle covering the surrounding area on the 3D earth.

I'm using Away3D 4.0, but as this is more of a math issue rather than an engine issue it might not be too relevant. As for my math skills, they used to be really good, but haven't used my 3D maths in a few years. So you might have to bare with me.

Thanks
3D drawing - circle on a sphere

Thursday, June 28, 2012

[Action Script] Clock Countdown Function Help June,2012

Hello,

I was wondering if someone could break down the following code for me and make it a bit easier so that i can just set a start date / end date.

Thanks.
Code: function displayDifference()
{
    nowTime = new Date();
    hoursLeft = ((((16-nowTime.getDate())*24) + (20 - nowTime.getHours())));
        //hoursLeft = (4 - nowTime.getDate()) * 24 + (19 - nowTime.getHours());
    if (hoursLeft >= 0)
    {
        timeRemaining.text = hoursLeft + ":" + padString(59 - nowTime.getMinutes()) + ":" + padString(59 - nowTime.getSeconds()) + "";
    }
    else
    {
        timeRemaining.text = "0H 0M 0S";
    } // end else if
} // End of the functionWhat i want to do is have a Start date of a value such as July 1st
and end date of July 31st

i'm not sure how similar this is to javascript esentially i want it to be like this.

Code: /* Date Animation  starts here*/
                                $(function () {
                                var austDay = new Date();
                                var austDay = new Date("June 30, 2012 21:00:00");
                                $('#countdown').countdown({until: austDay, layout:
                                                                '<div id="days" class="numbers">{dnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="hours" class="numbers">{hnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="minutes" class="numbers">{mnn}</div>'+
                                                                '<div class="spacer"></div>'+
                                                                '<div id="seconds" class="numbers">{snn}</div>'+
                                                                '</div>'});
                                                                });});
Clock Countdown Function Help

[Action Script] Dynamic image loaded into a Masked layer June,2012

I am trying to load images into a masked layer but the image just appears unmasked. Here is the code I am using to load the image. As you can see it is pretty standard stuff. You will note, though, that I am adding the child at the level of the masked layer.

ActionScript Code: public function loadImage(url:String):void {            imageLoader = new Loader();            imageLoader.load(new URLRequest("_art/" + url));            imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);            imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);                    }        public function imageLoaded(e:Event):void {            _parent.parent.mcOcular.addChildAt(imageLoader, 0);loadImage("butterfly.png")
I am creating a training tool to teach students how to use a light microscope. There will be anywhere from 10 to 30 slides that they can choose from and place on the tray. I load the image in the round viewport once they place the slide. The image loads properly, but it is not adhering to the round viewport mask. The whole image is seen on stage.

What might I be doing wrong? Has anyone else had this issue and, if so, what can I do to fix it. This is all in AS3, of course.

Thanks in Advance guys!
Dynamic image loaded into a Masked layer

[Action Script] Event Handler Function to Change States in another Component June,2012

Here is my situation. I have an application with an options menu. In its 'Main' component I have created an options menu that includes a drop down menu. This drop down menu allows the user to select between Type 1 and Type 2, which represent two different components (named type1 and type2, respectively) that take turns displaying below the options menu in the 'Main' component, depending on which one is selected.

If I have Type 1 selected then I would also like to have a few checkboxes in the option menu that allow the user to change views within the 'type1' component. I have created 4 different states in the 'type1' component, so I need to figure out how to create an event handler that sits in the 'Main' component but controls the state of the 'type1' component.

Is this possible? I tried to do the following to no avail:

Code: //Method executed when Type 1(A) checkbox is selected in the 'Main' component
//This method and its associated checkbox sit in the 'Main' component
protected function type1AHandler(event:Event):void
{
      type1.currentState = 'A'                                               
}Any ideas how to create an event handler that changes the state of a component that is instantiated in the active component? Thanks!
Event Handler Function to Change States in another Component

[Action Script] Connecting Flash to Php/MySQL June,2012

Hello. I am having a problem connecting flash to php/mysql. Here is my flash code:

Code: var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();

register_button.onRelease = function() {
        var valid:Boolean = validateForm();
        if(valid){
        //gather information and put in loadvars object
        lvSend.username = username1.text;
        lvSend.password = password1.text;
        lvSend.email = email1.text;
        lvSend.sendAndLoad("register.php", lvReceive, "POST");
        username1.text = "";
        password1.text = "";
        email1.text = "";
        gotoAndStop(1);
}
}
        lvReceive.onLoad = function(success:Boolean) {
if (success) {
    trace("ok");
}
else {
    trace("error");
    }
        }
function validateForm():Boolean{
        if(username1.text == "" || password1.text == "" || email1.text == ""){
                return false;               
}
        return true;
}Here is my php code:
Code: <?PHP
//Database Information
$dbhost = "xxxxxxxx";
$dbname = "xxxxxxxxx";
$dbuser = "xxxxxxxx";
$dbpass = "xxxxxxxx";
//Connect to Database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
//If no errors present with the username use a query to insert the data into the database.
$query = "INSERT INTO users(email,username,password)
VALUES('$email','$username','$password')";
mysql_query($query)or die(mysql_error());
mysql_close();
//Lets check to see if the username already exists
$checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");
$username_exist = mysql_num_rows($checkuser);
if($username_exist > 0){
echo "I'm sorry but they username you have chosen is already in use. Please pick another.";
unset($username);
include 'play.swf';
exit();
}
//If no errors present with the username use a query to insert the data into the database.
$query = "INSERT INTO users(email, username, password)
VALUES('$email', '$username', '$password')";
mysql_query($query)or die(mysql_error());
mysql_close();
echo "You have successfully been registered!";
//Mail user their information
$yoursite = 'MonkeyIsland';
$webmaster = 'xxxxxxxxx';
$youremail = 'xxxxxxxx';
$subject = "You have been registered";
$message = "Dear $username, you have been successfully registered at xxxxxx!
Here is your login information:
Username = $username
Password = $password
Please don't share this information with anyone.
Thanks,
$webmaster";
mail($email, $subject, $message, "From: $yoursite <$youremail>\nX-Mailer:PHP/" . phpversion());
echo "Your information has been mailed to your email address.";
?>I was wondering what could possibly be the problem. My button works and all, its just that it doesn't send it to the database. Can anyone give me any sort of help? I'll take any answers. Thanks!
Connecting Flash to Php/MySQL

[Action Script] how do i put a timer in properly? June,2012

I 've been away from Flash Prof. for quite a bit of time?

the lesson (that was ..seemed great;is great.)taught how to make a Timer-
var myTimer:Timer = new Timer(8000); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runMany);
myTimer.start();

function runMany(event:TimerEvent):void {
trace("runMany() called @ " + getTimer() + " ms");

say, i want to put this in Frame 1 Actions:how would i key it??

I tried copy & Paste into Frame 1 Actions(this)
I got - Expecting RightBrace before end of program?? Any Suggestions??
how do i put a timer in properly?

[Action Script] Creating Charts with Step Functions June,2012

Hi, I am trying to create a chart with an x-axis of days that has two series, a column and line series. The column series will have a bar for each day and I want the line series to be constant across a group of 7 days and then jump to a different level, where it will remain constant for another 7 days (i.e. create a step function). I am using an ArrayCollection object for the data so I currently have something like this:

Code: <fx:Script>
    <![CDATA[
         
          import mx.collections.ArrayCollection;

          [Bindable]
          private var levels:ArrayCollection = new ArrayCollection([
                      {DaysLeft: 14, Daily: 8, WeeklyAvg: 12.86},
                      {DaysLeft: 13, Daily: 10, WeeklyAvg: 12.86},
                      {DaysLeft: 12, Daily: 9, WeeklyAvg: 12.86},
                      {DaysLeft: 11, Daily: 14, WeeklyAvg: 12.86},
                      {DaysLeft: 10, Daily: 12, WeeklyAvg: 12.86},
                      {DaysLeft: 9, Daily: 18, WeeklyAvg: 12.86},
                      {DaysLeft: 8, Daily: 19, WeeklyAvg: 12.86},
                      {DaysLeft: 7, Daily: 20, WeeklyAvg: 15.86},
                      {DaysLeft: 6, Daily: 19, WeeklyAvg: 15.86},
                      {DaysLeft: 5, Daily: 22, WeeklyAvg: 15.86},
                      {DaysLeft: 4, Daily: 14, WeeklyAvg: 15.86},
                      {DaysLeft: 3, Daily: 13, WeeklyAvg: 15.86},
                      {DaysLeft: 2, Daily: 11, WeeklyAvg: 15.86},
                      {DaysLeft: 1, Daily: 12, WeeklyAvg: 15.86},  ])

    ]]>
</fx:Script>In the chart MXML code I have the following series declared:

Code: <mx:series>

      <mx:ColumnSeries xField="DaysLeft"
                    yField="Daily"
                    displayName="Days Left">
      </mx:ColumnSeries>

      <mx:LineSeries xField="DaysLeft"
                          yField="WeeklyAvg"
                displayName="Weekly Out at Current Pace">
      </mx:LineSeries>

</mx:series>This of course gives a straight line that changes values from 12.86 to 15.86 from day 7 to day 8. How could I make this line change values between day 7 and day 8 in the form of a step function?

Thank you very much for helping!
Creating Charts with Step Functions

Wednesday, June 27, 2012

[Action Script] Stencyl - A good tool? June,2012

Hi,
I'm used to working with Unity3D and I like the fact that it has a nice user interface, while keeping the ability to use code and create your own behaviours. I've seen that Unity3D now has Flash support, but this license costs an additional $400, and I started looking into some equivalents, dedicated to flash development, and stumbled upon Stencyl (stencyl.com). Now, I've seen on the site that Stencyl requires no coding, but does have a coding feature. Can I get your opinion on this engine, do you think it's worth using? Or do you know a better alternative?

Thanks,
Arne Gevaert
Stencyl - A good tool?

[Action Script] keyListener functions differently after first time on frame June,2012

A while ago I asked on these forums how to implement a pause feature in my game. It works great! However, I've just noticed that when you leave the frame (each frame of the main timeline holds the MCs for one level of the game) and return to it, pausing no longer works. I did some tracing to try and uncover what was happening, and it seems that anytime beyond my first "visit" to the frame, it fails to toggle isPaused = !isPaused and it executes pauseHUD == false AND pauseHUD == true. I've included the code (and omitted everything that is not relevant) below.

Code: onClipEvent (load) {

//Creates a listener for the Space Bar key and sets isPaused variable
var isPaused:Boolean = false;
var keyListener:Object = new Object();

//variable for pause sound and HUD
var pauseHUD = false;

//Loads the pause sound
pause_sound = new Sound();
pause_sound.attachSound("pause");

Key.addListener(keyListener);

keyListener.onKeyUp = function():Void
{
    if(Key.getCode() == Key.SPACE)
    {
        //toggle pause state
        isPaused = !isPaused;
                //start sound if not already playing
                if (pauseHUD == false) {

                        pause_sound.start();
                        pauseHUD = true;
                        trace("Executing A");
                        //code that shows HUD omitted

                } else if (pauseHUD == true) {

                        pauseHUD = false;
                        trace("Executing B");
                        //code that hides HUD omitted

                }
               
    }
}


function onEnterFrame():Void
{
       
 trace("isPaused = "+isPaused);
 trace("pauseHUD = "+pauseHUD);
       
    if(isPaused)
    {

    //code that pauses player and shows pause menu omitted
       
    }
    else
    {

    //code that unpauses player and hides pause menu omitted

    }
       
}In the interest of being thorough here's what I see in OUTPUT on my first visit to the frame when I press spacebar:

isPaused = false
pauseHUD = false
Executing A
isPaused = true
pauseHUD = true

And here's what I see on any subsequent visits when I press spacebar:

isPaused = false
pauseHUD = false
Executing A
Executing B
isPaused = false
pauseHUD = false

Any clue as to why this is and what I can do to prevent it from happening?
keyListener functions differently after first time on frame

[Action Script] [AS3] when I click my circles it doesn't match the randomly generated pattern. June,2012

i made a game in which you have nine circles and you have to click in the order randomly generated. when I click my circles it doesn't match the randomly generated pattern.

Heres my code:



import flash.events.MouseEvent;
import flash.events.Event;

var dict:Dictionary = new Dictionary();
dict[obj_1] = "1";
dict[obj_2] = "2";
dict[obj_3] = "3";
dict[obj_4] = "4";
dict[obj_5] = "5";
dict[obj_6] = "6";
dict[obj_7] = "7";
dict[obj_8] = "8";
dict[obj_9] = "9";


var pattern:Array = [dict[obj_1], dict[obj_2], dict[obj_3], dict[obj_4], dict[obj_5], dict[obj_6], dict[obj_7], dict[obj_8], dict[obj_9]];

var shuffledPattern:Array = new Array(pattern.length);

var randomPos:int = 0;
for (var i:int = 0; i < shuffledPattern.length; i++)
{
randomPos = int(Math.random() * pattern.length);
shuffledPattern[i] = pattern[randomPos];
pattern.splice(randomPos, 1);
}

trace(shuffledPattern);

//ONCLICK fuction
// circles dim on click
//trace circle value

var clickpattern:Array = []


obj_1.addEventListener(MouseEvent.CLICK, onclick)

function onclick (m:MouseEvent){

obj_1.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);
}

obj_2.addEventListener(MouseEvent.CLICK, onclick2)

function onclick2 (m:MouseEvent){

obj_2.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);

}

obj_3.addEventListener(MouseEvent.CLICK, onclick3)

function onclick3 (m:MouseEvent){

obj_3.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);

}

obj_4.addEventListener(MouseEvent.CLICK, onclick4)

function onclick4 (m:MouseEvent){

obj_4.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);


}

obj_5.addEventListener(MouseEvent.CLICK, onclick5)

function onclick5 (m:MouseEvent){

obj_5.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);

}

obj_6.addEventListener(MouseEvent.CLICK, onclick6)

function onclick6 (m:MouseEvent){

obj_6.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);

}

obj_7.addEventListener(MouseEvent.CLICK, onclick7)

function onclick7 (m:MouseEvent){

obj_7.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);
}


obj_8.addEventListener(MouseEvent.CLICK, onclick8)

function onclick8 (m:MouseEvent){

obj_8.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);

}

obj_9.addEventListener(MouseEvent.CLICK, onclick9)

function onclick9 (m:MouseEvent){

obj_9.alpha = 0.5
clickpattern.push(dict[m.currentTarget])
trace(clickpattern);
}

done.addEventListener(MouseEvent.CLICK, doneclick)

function doneclick (m:MouseEvent){
if (shuffledPattern == clickpattern){

trace("you win");
}
else{

trace("you lose")
}

}
[AS3] when I click my circles it doesn't match the randomly generated pattern.

[Action Script] BMP white background June,2012

Hello all. I am having problems importing a .bmp image to flash. I keep having the white background, is there a way to make that background transparent? I also remember long ago, I saw a tool called the magic wand and it removed white background to make an image transparent, but I can't find it in CS5, was it removed? Thanks for any help.

Regards
BMP white background

[Action Script] playing sounds from array names. June,2012

Hi, I have the following array:

Code: var sonidos:Array = ["do4", "sol4"];
how can I pass the proper names to play every sound in a function?

Currently I have:
Code: function PlayAllSam(arr:Array){
                var sizeArray = arr.length;
                trace (sizeArray+" elements.");

        for (var index in arr) {
                trace(index+" => "+arr[index]);
                arr[index].play(0,1);
        }
        }it works fine if in function I only write

Code: do4.play(0,1);How can I do this?

TIA.
playing sounds from array names.

[Action Script] Flash Menu Template Assistance June,2012

I am new to flash and trying to create a simple Flash Navigation Menu for my Site. I followed a Tutorial for creating one, but when I edit the text for 1 button, ALL the buttons change. How do I change the labels on the buttons?

Can Someone please guide me, and keep in mind I am entirely new to flash.
Flash Menu Template Assistance

Tuesday, June 26, 2012

[Action Script] Font Embedding Not Working June,2012

Just tried embedding a font with code for the first time but nothing is appearing.

I've attached the doc.

Can anyone help??

I have exported the font to actionscript and this is the code:

import flash.text.TextField;
import flash.text.TextFormat;

var txt:TextField = new TextField();
var fmt:TextFormat = new TextFormat();

fmt.font = "Calibri";

txt.embedFonts = true;
txt.wordWrap = true;
txt.multiline = true;
txt.text = "The quick brown fox jumped over the lazy dog.";
txt.defaultTextFormat = fmt;

addChild(txt);
Attached Files File Type: zip EmbedText.fla.zip (4.3 KB)
Font Embedding Not Working

[Action Script] [AIR] HTMLLoader window.open is not working June,2012

Hi frnds,

I have a web project developed in Flex which I have to make work standalone using AIR.

I created Air project and loaded the web application using flash.html.HTMLLoader.
The content is loading fine and working.

There are few buttons which open different links using javascript functions window.open.

The links are not opening. The javascript function is getting called using ExternalInterface and I placed alerts in that which is displaying.

The function contains simple window.open

PHP Code: window.open("http://www.google.co.in","Google"); 
I tried several solutions mentioned but none of them are working.

http://digitaldumptruck.jotabout.com/?p=672
http://soenkerohde.com/2008/09/air-h...-_blank-links/
http://cookbooks.adobe.com/index.cfm...ls&postId=9243

Kindly provide any assistance for this.
[AIR] HTMLLoader window.open is not working

[Action Script] How do you change Frames without rooting back to the start? June,2012

I have tried this and it does not work
var dreamworld: Boolean =false
if (Key.isDown(Key.SPACE))
{
if (dreamworld == false)
{
gotoAndPlay(2);
}
I have also tried "gotoAndStop(2);"
Please can someone help me :/
How do you change Frames without rooting back to the start?

[Action Script] Problem with matching input fields June,2012

Hi guys,

Im having a problem with my code, it doesn't seem to do what it needs to do, it keeps saying that i have entered a incorrect value and removes a life from me, Which is weird because it matches the variable

so heres the code

ActionScript Code: stop();Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;sendcall.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler_4);var number = String(5552326666);function fl_TapHandler_4(event:TouchEvent):void{    if(numerinput.text == number){    cc();    nextFrame();    }else if(numerinput.text != number){             removelives(1);             trace(numerinput.text);             }        }

So can anyone please point out where theres something wrong ?

Thanks,
Emmanuel lopen
Problem with matching input fields

[Action Script] Passing multiple parameters to function June,2012

Is it possible to pass more than one variable to a function?
As an array or anything else?

The variables may sometimes only one, sometimes more than three, etc.

Would very appreciate if someone can modify the code, thanks a lot!

ActionScript Code: disableKey("key1", "key2", "key3")function disableKey(target:Array){       for(var i=0; i<target.length; i++){            target[0].doSth;       }}
Passing multiple parameters to function

[Action Script] How to give function to multiple keys sequentially pressed? June,2012

I'm designing a platform game with standard left, right, jump mechanics.

However, I want to get this movement mechanic where if the user holds left or right key followed by the opposite direction key, the movement will continue in that direction but decrease in speed. Here's what I have:
Code: function onEnterFrame(event:Event):void
                {
                        if (leftKey == true)
                        {
                                if ( rightKey == true)
                                {
                                        playerJeebz1_mc.x -= mainSpeed/2;
                                }
                                else
                                {
                                        playerJeebz1_mc.x -= mainSpeed;
                                }
                        }
                       
                        else if (rightKey == true)
                        {
                                if (leftKey == true)
                                {
                                        playerJeebz1_mc.x += mainSpeed/2;
                                }
                                else
                                {
                                        playerJeebz1_mc.x += mainSpeed;
                                }
                        }
                }If I hold left then right, I move twice as slow.
But if I hold right then left, I end up moving left still.
Any ideas how I could fix this?
How to give function to multiple keys sequentially pressed?

Monday, June 25, 2012

[Action Script] changing frames June,2012

I need help with my code, I want to be able to push spacebar and for the frame to change without rooting.
if (Key.isDown(Key.SPACE))
{
gotoAndStop(2);
}
I am using Actionscript 2, please can someone help me :)
changing frames

[Action Script] Can't Access Global Variable Inside Function June,2012

I'm creating a multiplayer game with the SmartFoxServer API. I have a global variable declared in a function:

Code: if (type == "xml") {
                if (resObj._cmd == "findAfroCoins") {
                        _global.afro1frame = 2
                myDonut.av_pieces.av_afro1.gotoAndStop(afro1frame);The global variable is supposed to be used in a different part of the code but it needs to be called in that function because it needs to get data from my extension (SmartFox). Anyways, when I add a trace outside of the function, I get undefined, while if I put the _global variable outside of the function, it traces fine. So my problem is, how come the _global variable is undefined when created in the function? Thanks and sorry if a little bit of this has to do with SmartFox, the guys over there told me it was an actionscript problem.
Can't Access Global Variable Inside Function

[Action Script] xJSFL 1.0 is released June,2012

Just to let everyone know, xJSFL, an open source JSFL framework for creating tools and plugins for the Adobe Flash IDE, has finally been released as a 1.0:

http://www.xjsfl.com

If you're into building scripts and extensions for Flash, you'll want to check it out.

Cheers,
Dave
xJSFL 1.0 is released

[Action Script] TypeError 1009 won't go away June,2012

I know that this is a common error that has been addressed but I've read all the threads and Adobe's library explanation of the error--
but I still cannot figure out what's wrong with my code (it worked earlier).
EDIT: So I think my debugger is saying my problem starts in the addEventListener line:
Code: //this is the document class (MainCharacter.as), inside the Main Character class
                public function MainCharacter()
                {
                        init();
                }
                public function init():void
                {
                        stage.addEventListener(KeyboardEvent.KEY_DOWN,ifKeyD);
                        stage.addEventListener(KeyboardEvent.KEY_UP,ifKeyU);
                        addEventListener(Event.ENTER_FRAME,ifEnterFrame);
                }Output message:
Code: TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at MainCharacter/init()
        at MainCharacter()
TypeError 1009 won't go away

[Action Script] Insert Number into a sequence June,2012

I am looking for ideas to write a function that can insert an arbitary number into an arbitary sequence of numbers in an array, so that the result is in an ascending order.

ActionScript Code: var _objects:Vector.<int>; = Vector.<int>([ 1, 2, 4, 6, 7 ]);insertNum(5); // i want this: 1, 2, 4, 5, 6, 7
- I first thought of looping through the array and inserting the number after the first number that it is larger, but that would result in:
1, 2, 5, 4, 6, 7, where the 5 precedes 4. Similarly if I loop backwards, and I have the number 3 for example, then the result could be 1, 2, 5, 3, 6, 7

NOTE: Using sort, or sortOn() is NOT a possibility (as it is a simplified example, in the real case these numbers would be properties on a vector array of Objects)

PS: the array can only receive new elements using this method, so it will always be sorted, although it may have gaps
Insert Number into a sequence

[Action Script] Importing data from a XML to create a level June,2012

Hi guys,

I'm making a small platformer and planned on using Ogmo Editor to create my levels. Ogmo gives me the XML document, but for some reason I can't recreate the level. I've included images of the OEL file and my result vs the ogmo result. Also when I trace the length or crack ofr levelArray I get 887 instead of 864 (36x24).

ActionScript Code: public function createLevel(levelID,s):void        {            xmlLoader.addEventListener(Event.COMPLETE, LoadXML);            xmlLoader.load(new URLRequest("Level11.oel"));            function LoadXML(e:Event):void            {                levelXML = new XML(e.target.data);                xmlFilter = levelXML.*                for each (var levelTest:XML in levelXML)                {                    crack = levelTest;                }                                levelArray = crack.split('');                count = 0;                for(i = 0; i <= 23; i++)                {                    for(j = 0; j <= 35; j++)                    {                        if(levelArray[i*36+j] == 1)                        {                            block = new Platform;                            s.addChild(block);                            block.x = j*20;                            block.y = i*20;                            count++;                            trace("i ", i);                            trace("blockX ",block.x);                            trace("j ",j);                            trace("blockY ",block.y);                        }                    }                }                trace("count ",count);            }
Attached Thumbnails Click image for larger versionName:	Untitled-1.jpgViews:	N/ASize:	199.1 KBID:	38564 Click image for larger versionName:	Capture.JPGViews:	N/ASize:	68.3 KBID:	38565 
Importing data from a XML to create a level

Sunday, June 24, 2012

[Action Script] Booleans: how the heck do you GC them?!? June,2012

Hello All,

As it says above: I'm using AS3 and FlashDevelop, and I cannot seem to convince my compiler to GC it.

I tried the pretty standard options:

ActionScript Code: myboolean = null;delete(myboolean);
But for the null it says "col: 14 Warning: null used where a Boolean value was expected."
And delete I get "col: 11 Error: Attempt to delete the fixed property allDone. Only dynamically defined properties can be deleted."

And this is considering the Boolean is definited within a method as such:

ActionScript Code: var myBoolean:Boolean = false;
I appreciate that since it's within the method, when such as run it's course it should get garbage collected, but I like to be certain, and why can't I GC the Boolean when I've done the same for int, Array and Point? Isn't Boolean also an object??

So yea: if anyone knows how to GC the Boolean please let me know.

Thanks in advance for your time,

ReaperOscuro
Booleans: how the heck do you GC them?!?

[Action Script] Datagrid limit June,2012

I'm trying to add more than 20.000 item (.addItem) into a DataGrid with AS 3,
it always ended with an error.

Does anyone know what is the limit of a DataGrid,
how many row ( max. item) we can add into a DataGrid?

:confused:
Thank you!
Datagrid limit

[Action Script] How is this possible - facebook login? June,2012

Hi,

I develop AIR application for mobile devices and I'd like to connect my app to the facebook. Logging into facebook account works fine using FB AS3 Api: http://code.google.com/p/facebook-actionscript-api/. I wonder how is this possible that some apps use just FB login and user can retrieve his personal data from the application server? (like Shelby app) How can I authorize an user if I can't pass his login name and password to my server because of FB lin-app login.

For example:
1. An user login to my app by FB api login (no additional login screens!)
2. My app needs authorize him and after that my app server sends his personal data to the app (this is the problem)

Thanks
How is this possible - facebook login?

[Action Script] Architecture issue June,2012

Hi

I'm writing a parking meter application - it must calculate the payment based currentTime minus parkingBegin time.
The app must be fool-proof, also.
I've created 4 input fields - one for every digit in 24h format, input fields are limited to 0-2,0-9,0-6,0-9.
To access these input fields i've used ENTER_FRAME event, which calls function which checks whether input1 is filled, than advances to input2 and so on, thus making it possible to only enter proper digits in proper cells.

the question is following: after each calculation attempt triggered by user entering digit in input4 and pressing enter, the entire procedure must be started over. What is the correct way to return/close all open functions/procedures/calls/whatever.
I have no experience in OOP - this is my first app, so my question might sound a bit dumb...
Architecture issue

[Action Script] Make countdown timer stop at 00:00:00 June,2012

Hey guys!
I hope that someone can help me out here!
I made a countdown in flash but it seems when it's ended it continues counting. How can I make it stop at 00:00:00

Here's my code:
ActionScript Code: import flash.utils.Timer;import flash.events.TimerEvent;import flash.utils.setTimeout;import flash.media.SoundChannel;import flash.utils.*;import flash.system.ImageDecodingPolicy;import flash.display.BitmapData;import flash.events.KeyboardEvent;import flash.display.DisplayObjectvar customPanel:CustomPanel = new CustomPanel();addChild(customPanel);var timer:Timer = new Timer(30,0);var timer2:Timer = new Timer(Math.random() * 60000,1);var myTimer:Timer = new Timer(1200000,0);var secCntr:int = 0;var minCntr:int = 40;var hourCntr:int = 23;var currentTime:String;var soundRequest:URLRequest = new URLRequest("sounds/Flash Clock.mp3");var mySound:Sound = new Sound();var soundChannel1:SoundChannel = new SoundChannel();mySound.load(soundRequest);soundChannel1 = mySound.play();timer.addEventListener(TimerEvent.TIMER, setTime);timer2.addEventListener(TimerEvent.TIMER, surprise);stage.addEventListener(KeyboardEvent.KEY_DOWN, pressedKey);timer.start();timer2.start();customPanel.visible = false;function surprise(e:TimerEvent):void    {    trace("Surprise!");    customPanel.visible = true;    }function pressedKey(event:KeyboardEvent):void{    if(event.keyCode == 32)            if(contains(customPanel))    {    this.removeChild(customPanel);    }        {    keyDetector()              }    }function keyDetector():void    {    trace("The spacebar key was pressed");    }        function setTime(e:TimerEvent){        secCntr++;    if(secCntr == 60)        {        minCntr++;        secCntr = 0;        }            if(minCntr == 60)        {        hourCntr++;        minCntr = 0;        }    if (hourCntr >= 24)        {        hourCntr = 0;}    if(secCntr < 10)        {        currentTime = String(hourCntr) + ":" + String(minCntr) + ":0" + String(secCntr);            }        else        {        currentTime = String(hourCntr) + ":" + String(minCntr) + ":" + String(secCntr);        }    countdown_txt.text = currentTime;     }
Hope someone can help me out.

Greets,
Anne-Loes
Make countdown timer stop at 00:00:00

[Action Script] shapeFlag hitTest still using the bounding box? June,2012

On one frame of my game, I have two movie clips. One is the boundary, which is a big block of paint with an empty path erased into it. The other is a player, who is meant to walk through the path. I'm trying to use a shapeflag hitTest so that I dont need to create tons of separate hitTests in order to make the player stay inside the path. My problem is that this current code is still using the boundary's box to determine the hitTest. Does anybody know why this is?

Code: onClipEvent(enterFrame) {
        if(this.hitTest(_root.dude.body._x,_root.dude.body._y,true)) {       
                        _root.left=false;
                        _root.right=false;
                        _root.up=false;
                        _root.down=false;
          } else {
                          _root.left=true;
                        _root.right=true;
                        _root.up=true;
                        _root.down=true;
          }
}(I'm also using a separate movieclip inside the player called "body" for the hitTest since the players head is big and in the code for the player's movement, left, right, up or down need to be true for the player to move)
shapeFlag hitTest still using the bounding box?

Saturday, June 23, 2012

[Action Script] setStyle doesn't work with an array of images June,2012

Hey, I'm new to these forums, and I have a problem that's been driving me up the wall for over a week now, I was wondering if anybody here could help:

Basically, I'm trying to make an itemrenderer for an advanceddatagridcolumn that renders icons. The image is embedded in one class, passed to the datagrid API, and then passed from there to the itemrenderer, and when I do

Code: setStyle("icon", image)where image is defined in the previous line as the relevant image class, it's applied properly according to the trace I did, but the image isn't showing up. I'm getting no errors, no crashes, not even any failed try blocks, but the image just won't show up. When I attempt to embed it directly in the itemrenderer, it won't let me embed with a source that's a string variable rather than a raw string.

Does anybody know what my problem might be?
setStyle doesn't work with an array of images

[Action Script] flash 11.3 doesn't let you create projector June,2012

hello, been working with flash develop and stage3d and been exporting it on a projector to test it on other computers but I updated my flash SDK to 11.3 so I can use the releaseOutside but now when I open the swf and go to the file menu -> create projector. the Option is greyed out, its disabled. I'm not so sure if this is a bug or they are purposely blocking people from exporting swfs to exe projectors. Been looking for the internet and I'm not the only one. Does anybody know anything about this???!

Thanks!
flash 11.3 doesn't let you create projector

[Action Script] Cesar cipher June,2012

Need to make program that deciphres cesar cipher
Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher: DEFGHIJKLMNOPQRSTUVWXYZABC
As you see, cesar cipher is alphabet + 3 characters forward and a,b,c at the end.
So if i type "the quick brown fox jumps over the lazy dog" i should have that translated like this "WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ"
Cesar cipher

[Action Script] How to load folder of bitmaps? June,2012

How to load a folder of bitmap images?

This is the closest I've gotten, loading the names of the images,

of coarse I want the images,



import flash.filesystem.File;
import flash.events.Event;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.display.Bitmap;

var directory:File = File.documentsDirectory;

directory.browseForDirectory("Select Directory");
directory.addEventListener(Event.SELECT, onSel);

function onSel(event:Event):void
{
directory = event.target as File;
var files:Array = directory.getDirectoryListing();
for (var i:int = 0;i < files.length;i++){
trace(files[i].name);

}

}
How to load folder of bitmaps?

[Action Script] Flash issues June,2012

I have a project I been working on and it is pretty huge. Has a file loading and unloading a lot of child swfs and each child swf doing a lot of stuff on its own. Its all set up using the pureMVC framework and it works fine. Well just about.

We have clients using different versions of flash players . And some of them dont want to upgrade flash players or cant upgrade flashplayers .And some still use flash player 9 . So we end up targeting the file to flashplayer 9. I use cs5.5 and code in as3 .

So issue is this. I create a swf file with the required functionality. Works fine on its own.No issue what so ever . When I publish the main swf that handles the loading and unloading of child swf that works fine as well. The problem comes when we start to embed the main swf in html. There are these weird cases where sometimes the child swf doesnt tween completely. Like a simple gotoAndPlay will stop mid way during a tween. so will never hit a stop frame on the timeline at all or does any functionality that needs to happen when the timeline reaches the frames. or it wont read the timeline scripts due to which it will just miss the stops on the timeline and keep looping through the movie and stuff like this.To make it even worse the same child swf works fine one time. then the next time it is buggy and this is random and sporadic. To cap it all off sometimes it works on one computer running a different browser different flash player version and not on other computers. I dont know if there is anywhere I can look to find a fix for this issue .Or atleast explanation for why this happens. Is there a as3 loader code I m missing ?

Sorry to have wrote a essay there .This problem just does my head in.
Flash issues

[Action Script] Array collision problem... June,2012

Hey. So I've been having a lot of trouble trying to get a character in my platformer to detect collisions with an array properly. I've been scouring the internet for a couple days now for a solution but nothing I've seen seems to work properly.

Basically I just want the normal landing on tiles and not falling through them thing. But he lands just fine on the last tile in the tiles array (box3) but falls through when I try to walk him onto others.

Here's the code:

ActionScript Code: var yspeed = 0;var gravity = 0;var accel = 0.5;var maxvel = 4;var speed = 6;var tiles:Array = new Array();tiles[0] = box1;tiles[1] = box2;tiles[2] = box3;var playr = buddy;buddy.addEventListener(Event.ENTER_FRAME, collision);function collision(Event){    for (var i:int = 0; i < tiles.length; i++)    {        if (playr.hitTestObject(MovieClip(tiles[i])))        {            landed = true;        } else {landed = false}    }}stage.addEventListener(Event.ENTER_FRAME, grav);function grav(Event){    if (landed == true)    {        accel = 0;        maxvel = 0;    }    if (landed == false)    {        maxvel = 4;        accel = 0.5;        buddy.y = yspeed +=  gravity;        gravity +=  accel;        if (yspeed == maxvel)        {            yspeed = 0;            buddy.y = yspeed +=  maxvel;        }    }}
(Buddy is the character and the boxes are the tiles that I want him to land on.)
Also, if I'm going about this completely wrong, can someone suggest a better way to do this?
Array collision problem...

Friday, June 22, 2012

[Action Script] Drawn TextField vs scripted TextField June,2012

Does anyone know why I can define the .text property of a text field in a nested movie clip from its grandparent when the text field has been created using the drawing tools but not when I create it using action script?

In my file I have an input text field in the top left, a black button, and a green button. Each letter inputted is traced to the output panel and the black button traces the .text property to the output panel (just for my own learning). The green button opens up a movie clip within a movie clip that displays the inputted text.

I've attached the two files in question - one that works and one that doesn't.

Any possible answers to this would be most welcome! Sorry if it's obvious.

Thanks.
Attached Files File Type: zip TextFields.zip (20.2 KB)
Drawn TextField vs scripted TextField

[Action Script] Firefox 'back' button kills Flash June,2012

Hello,

I've been searching online in general for several hours and specifically on actionscript.org for the last few minutes to try and find a solution for the following issue that only seems to occur in Firefox:

1.) Click on a button in some Flash content and navigateToURL using a target of '_self'
2.) Click the browser's 'back' button to return to the page you came from
3.) The button in the flash content no longer works.

It seems like this is a FF issue more than anything. I've tried the following solutions to no avail:

- Force the Flash content not to cache
- Use ExternalInterface to check the browser type and if Firefox, use ExternalInterface to call a js function on the HTML page which sets the focus on some other non-flash HTML element.

If anyone has run across this before and has had some success resolving it, please let me know.

Thanks!
Firefox 'back' button kills Flash

[Action Script] array/function help June,2012

Hi, I'm pretty new to actionscript and I am working on avatar customization. I have 2 avatars, and there are 10 options to change their style(shirt, pants, shoes, etc) and color, which are movieclips that use frames.
I would like to be able to have it so if I change the avatar's shoes, shirt, etc.. when I hit the 'next character' button, the avatar I was editing stays how it was when i return back to it instead of resetting to default clothing and color(frame 1 everything). Is there any easy way to do this? I believe an array would be involved and a separate function but I have no clue how to do it.
Thank you!
array/function help

[Action Script] Adobe Acrobat Custom Stamp June,2012

Not sure if this is the right place, plus I'm a newb. I'm trying to create a custom stamp in Acrobat, with a date and time stamp.

When I get to the end of the process and save my file, the time and date is missing or it stays on what ever time I put it in. So basically when I try to use it as a stamp the time is always wrong.

Any help would be great, I've been fighting this for 2 solid days.

I'm using this link as a guide, see link image.
Attached Thumbnails Click image for larger versionName:	stamp.JPGViews:	N/ASize:	32.0 KBID:	38555 Click image for larger versionName:	stamp2.JPGViews:	N/ASize:	28.7 KBID:	38556 Click image for larger versionName:	link.JPGViews:	N/ASize:	15.1 KBID:	38557 
Adobe Acrobat Custom Stamp

[Action Script] simple login form June,2012

Hi everyone,

First post on the forum so I hope I'm posting this on the right place. I'm pretty new to AS and I am trying to make a simple login page but.... it's not doing the way I want it to go.

I create 2 input fields nametxt and passtxt, and a login button btn_login (a movie clip)

When I enter the name and password into the fields I get the message incorrect username / password, while I entered the exact information.

Here is the script :
Code: stop();

var cMenu:ContextMenu = new ContextMenu();
cMenu.hideBuiltInItems();
contextMenu = cMenu;


passtxt.displayAsPassword = true;

btn_login.buttonMode = true; // show hand cursor


btn_login.addEventListener(MouseEvent.CLICK, loginUser);

function loginUser(e:MouseEvent):void
{
       
        if(nametxt.text == "admin" && passtxt.text == "password")
        {
                gotoAndPlay(2);
        }else {
                //otherwise show an error message
                var alert:TextFormat = new TextFormat();
                alert.color = 0xff0000; //red font
                display_txt.text = "Incorrect username or password";
                display_txt.setTextFormat(alert);
        }
}Thank you in advance
simple login form

[Action Script] Problem with Panel Layouts June,2012

I am trying to design a UI in Flash Builder 4.6 and am having an issue getting Panels to stay within the container they should be constrained to. I have a BorderContainer that spans the top 14% of the window and 100% of the width. I would like to add several Panels to this BorderContainer so that I can have multiple different 'sections', each with its own Panel title and several drop down menus/radio buttons/etc within each. My code is shown below with the first two panels included:

<!-- Top Container -->
<s:BorderContainer width="100%" height="14%">

<s:layout>
<s:HorizontalLayout/>
</s:layout>

<!-- Top, A Container -->
<s:Panel width="280" height="100%"
dropShadowVisible="false"
title="Display Options">
</s:Panel>

<!-- Top, B Container -->
<s:Panel width="280" height="100%"
dropShadowVisible="false"
title="Workstation Options">
</s:Panel>

</s:BorderContainer>

I can get these constraints to work (so that the panels are not taller than the bordercontainer) but when I make any further adjustment to the interface they will change size (becoming larger than the BorderContainer that they are in). I'm not sure why this is happening because I have them inside the BorderContainer and have specified that they remain 100% of its size. For some reason though they like to change size in relation to their container.

Can anyone tell me how to fix this? Thank you!
Problem with Panel Layouts

Thursday, June 21, 2012

[Action Script] XML Loading Incorrectly Sometimes? June,2012

I have a flash site that loads an XML list of prices and info. The site is brodericktower.com.

The problem is happening on the Pricing Page. The rental rate and availability are wrong for some units. For example, unit 13K will give a price and avail, however, it should be marked Reserved. I have yet to see this problem myself, but I'm getting complaints that the info is not always coming up correctly.

I'm not sure if this is a browser issue or a mac/pc thing. I've tried several browsers on my pc and I don't see the problem. I'm getting many complaints, but I can't seem to recreate the problem to know how to fix it.

Does loading an xml file have any known compatibility issues?

Any ideas? I'm not sure how to test this and fix this problem.
XML Loading Incorrectly Sometimes?

[Action Script] Using SQLlite with Air June,2012

I'm new to using SQL

The following example has the user load an image, converts the image to a byteArray, and inserts the byteArray in a table named 'images'.

When the user presses a button the data is retrieved from the database.

The problem is retrieving the byteArray from the database, I get Error #1034: Cannot convert object to flash.utils.ByteArray.

Possibly the problem is that I'm SQL illiterate.




import flash.filesystem.File;
import flash.events.Event;
import flash.display.Loader;
import flash.utils.ByteArray;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.data.SQLStatement;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.data.SQLConnection;
import flash.errors.SQLError;
import flash.data.SQLResult;
import flash.data.SQLCollationType;

/* ***************************************
* *
* Establish Connection and make *
* *
* table *
* *
*************************************** */

var conn:SQLConnection = new SQLConnection();
var folder:File = File.applicationStorageDirectory;
var dbFile:File = folder.resolvePath("DBTest.db");

try
{
conn.open(dbFile);
trace("database created");
}
catch(error:SQLError)
{
trace("error message: " + error.message);
trace("details: " + error.details);
}

var stat:SQLStatement = new SQLStatement();
stat.sqlConnection = conn;

var sql:String =
"CREATE TABLE IF NOT EXISTS images(" +
"imageID BLOB" +
")";

stat.text = sql;

try
{
stat.execute();
trace("Table Created");
}
catch(error:SQLError)
{
trace("Error Message: " + error.message);
trace("Error Details: " + error.details);
}

var bytes:ByteArray = new ByteArray();


/* ****************************
* *
* Create Button *
* *
**************************** */

var but:Sprite = new Sprite();
but.graphics.beginFill(0x0000dd);
but.graphics.drawRoundRect(400,30,40,40,10,10);
but.graphics.endFill();
addChild(but);

but.addEventListener(MouseEvent.CLICK, gogo);
function gogo(event:MouseEvent):void
{
out();
}

/* **************************
* *
* Load Image *
* *
************************** */

var file:File = File.documentsDirectory;
file.addEventListener(Event.SELECT, handleSelectPicture);
file.browseForOpen("Select Picture");


function handleSelectPicture(event:Event):void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.CO MPLETE, handleLoadPicture);
loader.load(new URLRequest(event.target.url));

}

function handleLoadPicture(event:Event):void
{
// load bitmap

var loader:Loader = Loader(event.target.loader);
var image:Bitmap = Bitmap(loader.content);

// get Bitmap data

var imageData:BitmapData = new BitmapData(image.width,image.height,false);
imageData.draw(image);
var aa:Number = new Number();
aa = image.height / image.width;
var image3:Bitmap = new Bitmap(imageData);
image3.width = 200;image3.height = 200 * aa;
addChild(image3);

// convert to ByteArray

var rect:Rectangle = new Rectangle(0,0,image.width,image.height);
var bytes:ByteArray = imageData.getPixels(rect);


/* ************************
* *
* Insert Image *
* Into Table *
* *
************************ */

var statIn:SQLStatement = new SQLStatement();
statIn.sqlConnection = conn;

var sql2:String =
"INSERT INTO images(imageID) " +
"VALUES ('bytes')";

statIn.text = sql2;

try
{
statIn.execute();
trace("Image inserted");
}
catch(error:SQLError)

{
trace("Error Message: " + error.message);
trace("Error Details: " + error.details);
}

}

/* ********************
* *
* Select ByteArray *
* From Table *
* *
******************** */


function out():void
{
var statOut:SQLStatement = new SQLStatement();
statOut.sqlConnection = conn;

statOut.text = "SELECT CAST(imageID as ByteArray) FROM images";
statOut.execute();

try
{

var ex:SQLResult = statOut.getResult();
trace(ex.data[0]);
var by:ByteArray = ex.data[8];
trace(by);
}
catch(error:SQLError)
{
trace("Error Message: " + error.message);
trace("Error Details: " + error.details);
}

}
Using SQLlite with Air

[Action Script] [AS2] Testing SharedObject behaviour for a save game June,2012

Hi, I've been looking at the following tutorial while I implement a save feature in the game I'm making:

emanueleferonato.com/2008/01/02/managing-savegames-with-flash-shared-objects/

If I can somehow test it out I think I can get it to work with my game, but it doesn't seem to be working when I publish (whether I use the swf directly or the html file). It could be that I'm not manipulating the AS correctly, or simply that it's not published to a domain? Either way, it doesn't seem to be creating a file in the #SharedObjects folder on my mac.

Am I able to test this locally? If not, what would be the best/safest way to go about testing it?

Thanks!
[AS2] Testing SharedObject behaviour for a save game

[Action Script] Is it possible to make a flash site full screen without a user activating full screen June,2012

So I have no problem getting a Flash site full screen with a button but then I got thinking.... Is it possible to make a flash site full screen without a user activating full screen mode via a button basically when the site comes on can you make the site go full screen automatically?
Is it possible to make a flash site full screen without a user activating full screen

[Action Script] How to Restart MovieClip with stop in a Main Timeline Looping Animation? June,2012

Hi AS3 Guys,

I need help with my flash work regarding the looping animation.

--------------------------------------------------------------------------------------------------------------------
Problem Case: I have Main Timeline which is a looping animation, within the Main Timeline there is movieclip named "MC" ( inside the movieclip timeline, I put stop(); so that the movieclip will not play automatically within the main timeline and wait for the animation to be finished ), but the problem is when the 2nd iteration of animation, the movie clip stops and doesnt restart its animation.
Note:
The total length of animation is 11secs @ 18FPS with a total of 199Frames
The movieclip is a only part of the main animation that had own animation itself.
I need AS3 code.

Question: How do I restart the movieclip animation in every iteration/loop of the main timeline animation. What am I going to do? :confused:
--------------------------------------------------------------------------------------------------------------------

I tried some sample on the internet but no one works for me. Any answer would be great help. Thanks! :)
How to Restart MovieClip with stop in a Main Timeline Looping Animation?

[Action Script] Post anything you want June,2012

http://sfxworks.net/post.php
It gets saved for a long time!
Post anything you want

Wednesday, June 20, 2012

[Action Script] button code help June,2012

hey guys... im very new to flasha dn AS3... i have been given code


fred.addEventListener(MouseEvent.CLICK, playMovie);


function playMovie(event:MouseEvent):void
{
event.currentTarget.play();
}


and have NO idea how to use it... i have changed the name from fred to bird as that is what mine is called now im confused becasue on the example and where i have gotten the code (from my tafe teacher) his layer is called fred... so i have replaced it with what my layer is called... bird... and then a girl in class has then said that where is says movie that i need to replace that with bird as well and also change the play to... gotoandplay and put a 2 in the brackets and i have done both of these and also added the stop code to my movie clip from my libary and still nothing it my bird is just on a loop like the rest of my stuff???
and then someone said something about an istance name? once i have imported my image from illustrator and have changed them all to a movie clip i can click on each individual part and change the instance name... but how would that work if there is over 10 parts with the same name?
:/ someone please help me
button code help