jeudi 31 mars 2016

Why can't I load this previously serialized object?

This class is serializable:

   package com.things {
        public class MySerializableObject {
            public var intVals:Array;
            public var numVals:Array;
            public var stringVals:Array

            public function MySerializableObject() {

            }

            public function init(ints:Vector.<int>, nums:Vector.<Number>, strings:Vector.<String>) {
                intVals = new Array();
                for each (var i:int in ints) {
                    intVals.push(i);
                }
                numVals = new Array();
                for each (var n:Number in nums) {
                    numVals.push(n);
                }
                stringVals = new Array();
                for each (var s:String in strings) {
                    stringVals.push(s);
                }
            }
        }
    }

We can do this:

registerClassAlias("com.things.MySerializableObject", MySerializableObject);

And then do this:

var mso:MySerializableObject = getInitializedMSO();
sharedObject.data.mso = mso;
sharedObject.flush();

var newMSO:MySerializableObject = sharedObject.data.mso as MySerializableObject;
trace(newMSO); //outputs "[Object MySerializableObject]"

However, if we restart the application and do this:

registerClassAlias("com.things.MySerializableObject", MySerializableObject);
var previouslySavedMSO:MySerializableObject = sharedObject.data.mso as MySerializableObject;
trace(previouslySavedMSO); //outputs "null"

Flash apparently fails to read the saved object as a MySerializableObject after we close and re-open the application. We can see, by inspecting the SO in a debugger, that the data is still there, but Flash can't typecast it back into its original data type anymore. Is this the expected behavior? If not, what is the problem and how can we fix it?

Keep getting error#1502 for this loop in as3

It's supposed to be for a rhythm game, where while the mc is on the stage, the boolean keeps switching back and forth from true to flase and you have to catch it at the right time. But I keep getting an error...

while (theBeat)
{
  if (theBeat.currentFrame < 5)
    {
    onBeat = true
    trace(onBeat)
    }

  if (theBeat.currentFrame > 5)
    {
    onBeat = false
    trace(onBeat)
    }
}

How to call AS3 code from a web page inside an Adobe AIR application?

We have an Adobe AIR application that sometimes loads a web page. On one of these web pages there is a hyperlink. When the hyperlink is clicked I want an AS3 function to be called. I know how to call a JavaScript function when the hyperlink is clicked, but within the JavaScript function how do I call my AS3 function?

In all the examples I can find the Flash is a SWF on the webpage and is thus inside a DOM element. So in the code examples they call the AS3 function on a DOM element like so:

function sendTextToAS3() {
    var Txt = document.getElementById('htmlText').value;
    var flash = document.getElementById("as3_js");
    flash.sendTextFromJS(Txt);
    document.getElementById('htmlText').value = "";
}

But in my case the Flash is not a SWF inside a DOM element, instead the Flash is the whole Adobe Air app and there is no DOM element with a SWF. So what do I call my AS3 function on if I can't do it via a DOM element?

RTMFP communication between Air and SWF

I'm curious to know if it is possible to communicate between AIR/AIR mobile and SWF web apps using RTMFP. I was testing a demo for both Air and Flash to connect to the Cirrus Service. It seems that when I try to connect to the server, I can only see peers that uses the same platform even with the same source code and NetGroup name.

Am I missing some steps or any ideas on how to make this work?

Dynamic access to variable from another namespace in actionscript 3

How can I get dynamic acces to variable from another namespace?

public namespace myNamespace = "http://ift.tt/1pNFBiH";

...

public var _publicVar: String = "foo";
myNamespace var  _namespaceVar: String = "bar";

...

trace(_publicVar);
trace(myNamespace::_namespaceVar);
trace(this["_publicVar"]);
trace(this["_namespaceVar"]); // <<< Exception

I can see this variable wthen I call describeType() and think it's possible

<variable name="_namespaceVar" type="String" uri="http://ift.tt/1pNFBiH">
...
</variable>

How to get the week number in the month of a Date - AS3 (Actionscript 3)

How would I get the week number in the month of a Date?

I can retrieve the week number in a year w/ getWeekOfTheYear (d:Date) but a calculation based around that will prove difficult - any help is greatly appreciated

Returned value I would expect would typically range from [0 - 4]

ActionScript 3 - startTouchDrag X axis only?

I have an object on the stage called, square_mc, currently I have a function which is using the startTouchDrag method to move my object wherever the user touches the screen. But I dont want my object to move on the Y axis (Up and down) is this possible.

Heres my code...

//touchpoint
var touchPoint;

//When user touchs stage fun touchDown function.
stage.addEventListener(TouchEvent.TOUCH_BEGIN, touchDown ); 

//When the user stops touching the screen run.
stage.addEventListener(TouchEvent.TOUCH_END, touchUp );     

    //When user touchs on screen run. 
    function touchDown(evt:TouchEvent):void
     {

        //TouchPoint = localX.
        var touchPoint = evt.localX;

        //Start the touch drag on the square_mc, moves where the user touche   the stage.
        square_mc.startTouchDrag(evt.touchPointID);

        trace("User touched");

    } // end function


    function touchUp(evt:TouchEvent):void
    {

        //More code will be written.
    }

Many thanks

Are there any event listeners for windows taskbar property change in Action script 3

I wants to know are there any event listeners for windows taskbar property change in Actionscript-3 because i wants to adjust my application canvas window size according to taskbar height i.e if i will change the windows taskbar height, accordingly my application canvas size will change.

Does anyone have an idea what are the event listeners or any other possible ways to solve this problem ?

AS3 protected method are inaccessible for subclass in mxml

for a parent class A contains a protected method f() :

public class A {

protected  function f():void
        {
        }
}

public class B extends A{
}

when i create an mxml and create an instance of B with imports all of A and B (are in the same package)

B b = new B();
//the problem :
b.f(); // inaccessible method !!

How to clone an Online Game

I know it's not an easy job to clone an online game. Especially these modern games. I am an application developer and i can understand coding. I need someone who could help me to clone an online game like 8 Ball pool , clash of kings or any other browser based game. I don't want to "steal" the coding to develop a new game. I just want to clone it , make few changes and host it. I wont be earning / charging anything off it. If anyone could help me and point in the right direction, that'd be helpful !

Thank You.

Find the limit of shared object

I have been trying to play around with shared object , I need to alert the user what i am going to save in shared object , but whenever i call flush() i cant get the current limit of storage i.e as of now 100 KB. is there any way to get the current limit of shared object for a particular domain ?

i even tried flush status , but flush status is created only after it shows up the security panel , i need to know the limit even before flush calls the security panel.

i need data just like this have the limit http://ift.tt/GN88dT

mercredi 30 mars 2016

defining as3 object keyword in createjs

does createjs support as3 "object" keyword. while converting to createjs i am getting error q undefined . the error was coming from this line var question:String = randomQ.q;
anyhow i guess . createjs could not convert qaObject as object . thats why dot operator variable qaObject.q was undefined. and undefined variable error was coming from randomQ.q;

for(var i:Number=0; i<questions.length; i++) {
        var qaObject:Object = {};
        qaObject.q = questions[i];
        qaObject.a = answers[i];

        qaArray.push(qaObject);  //Add object to qaArray
    }

var question:String = randomQ.q;  

ok. i converted this like below : just removed the object keyword and put toString(); after q.

/* js 
for(var i=0; i<questions.length; i++) {
        var qaObject = {};
        qaObject.q = questions[i];
        qaObject.a = answers[i];

        qaArray.push(qaObject);  //Add object to qaArray
    }

    var question = randomQ.q.toString();

*/

Getting an error, text.match error when no results exist

I have code that looks like this

if (consearch.text.match(/kau$/).length >= 0)
{ 
trace("test"); 
}

which works fine if consearch.text value ends with "kau" unfortunately when it does not end with "kau" I get a 1009 error

Am I missing something?? Not sure why its giving me this error

Flex Mobile: Test Resolutions Greater than Screen Size

Flash Builder has an Emulator for mobile devices of any resolutions.

My questions are the following:
1) When testing for devices with resolutions greater than my screen size, is it still reliable to use the FB Emulator?
2) What are other alternatives that can I use for debugging purposes with FB?

How to save input text as bitmap in as3? Can anyone please tell me why this code is not working?

1.How to save input text as bitmap in as3? Can anyone please tell me why this code is not working?

Some class files are imported here

import flash.text.TextField;
import flash.display.MovieClip;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.PNGEncoderOptions;
import flash.utils.ByteArray;
import flash.net.FileReference;
import com.adobe.images.JPGEncoder;
import flash.events.MouseEvent;
import fl.motion.MotionEvent;

Code starts here

var bitmapdata: BitmapData = new BitmapData(200, 200);
bitmapdata.draw(txt);

var xmv: MovieClip = new MovieClip();
xmv.graphics.beginBitmapFill(bitmapdata);
xmv.graphics.drawRect(0, 0, 200, 300);
xmv.graphics.endFill();

var jpgEncoder: JPGEncoder = new JPGEncoder(100);
save.addEventListener(MouseEvent.CLICK, click)


function click(e:MouseEvent) {

var imgByteData: ByteArray = jpgEncoder.encode(bitmapdata);
var file = new FileReference();
file.save(imgByteData, "Image.jpg");

}

How do I add this code into my Flash Project?

I'm making an animated movie with Flash and I found this code for a cool bouncing ball effect. I'm unsure about how to add it to my project in Flash and would appreciate a walkthrough of it! Thanks!

CODE:

private const NUM_BALL:int = 24;
private var loadingBall:Vector.<Shape> = new Vector.<Shape>(NUM_BALL);
private var timeStep:int = 0;
private const BALL_HEIGHT:int = 40;

public function animateBalls(e:Event):void
{
    for (var i:int = 0; i < NUM_BALL; i++ )
    {
        loadingBall[i].graphics.clear();
        loadingBall[i].graphics.beginFill(0x0B5F95);
        loadingBall[i].graphics.drawCircle(455+5*i,getY(i,timeStep),2);
    }
    timeStep++;
}

public function getY(i:int, t:int):int
{
    return 260 + BALL_HEIGHT/2 * (1 + Math.sin((timeStep * (i/500 + 0.02)) % 2*Math.PI));
}

if statements and textinput value

If I have a textfield, and I want to use an IF statement to check that text field, for example, I can do this

if (thistxt.text=="query")
{  
thisbool = "true";
}

Now let's say I want to use an IF statement to call upon that same textfield but I don't want to pull that entire phrase, (query) maybe just the beginning or end of it, how could I do something like that? Let's say I want to activate the IF statement if that textfield contains or ends with "ery" but is not necessary perfectly equal to "ery".

ActionScript3 issues

So I’m having some issues with ActionScript. I’m creating a project where you are able to click on a penny and drag it to a scratch off card, where you then scratch off the coating and text is revealed. Everything is composed of two layers. The bottom layer is an image of the card with the text on it( I turned it into a bitmap). The top layer is a rectangle (scratch off coating) with a solid fill that I turned into a movie clip with a property name of maskee3. So far I was successful. Where I ran into problems is when I tried adding another scratch off card to the stage. I did the same process, turned the card into a bitmap and the rectangle scratch off coating (top layer) into a movie clip with a property name of maskee4. When I hit preview movie it still only scratches off the initial card. I honestly don’t know what to do and how to fix this to make it so it scratches off all of them. Below is the coding I did, I have just been shooting in the dark at this point. Any help would be appreciated. Thanks!

/* Drag and Drop
Makes the specified symbol instance moveable with drag and drop.
*/

penny.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);

function fl_ClickToDrag(event:MouseEvent):void
{
penny.startDrag();
}

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);

function fl_ReleaseToDrop(event:MouseEvent):void
{
penny.stopDrag();


}

//start code for scratch off//


/*************************
MASKING
**************************/

/*
Initial variables
*/
// Change lineSize to control size of your eraser
var lineSize:Number=4;
// doDraw is true when user's mouse is down
var doDraw:Boolean=false;
// resumeDrawing is true when user drags their mouse off stage while drawing
var resumeDrawing:Boolean=false;

/*
Create a bitmap to act as our image mask
Add it to stage & cache as bitmap
*/
var erasableBitmapData:BitmapData = new BitmapData(400, 400, true,                0xFFFFFFFF);
var erasableBitmap:Bitmap = new Bitmap(erasableBitmapData);
erasableBitmap.cacheAsBitmap = true;
addChild(erasableBitmap);

/*
Set the erasable bitmap as a mask of our image & cache image as bitmap
*/


maskee3.cacheAsBitmap = true;
maskee3.mask = erasableBitmap;

maskee4.cacheAsBitmap = true;
maskee4.mask = erasableBitmap;


/*************************
ERASER
**************************/

/*
Create a sprite for drawing the eraser lines onto
Set its lineStyle, and move the line to the current mouse x,y
*/
var eraserClip:Sprite = new Sprite();
initEraser();
function initEraser():void{
eraserClip.graphics.lineStyle(lineSize,0xff0000);
eraserClip.graphics.moveTo(stage.mouseX,stage.mouseY);

}

/*
Create a bitmap to copy the erased lines to.
This is required to ensure a smooth erase effect (applying eraserClip 
directly to erasableBitmapData leaves jaggy edges  around alpha areas. 
If anyone knows why, I'd love to know!)
*/
var drawnBitmapData:BitmapData = new BitmapData(400, 400, true, 0x00000000);
var drawnBitmap:Bitmap = new Bitmap(drawnBitmapData);

/*************************
MOUSE EVENTS
**************************/

/*
Add event listeners for mouse movements
*/
stage.addEventListener(MouseEvent.MOUSE_MOVE,maskMove);
stage.addEventListener(MouseEvent.ROLL_OUT, maskOut); 
stage.addEventListener(MouseEvent.ROLL_OVER,maskOver);
stage.addEventListener(MouseEvent.MOUSE_DOWN,startDrawing);
stage.addEventListener(MouseEvent.MOUSE_UP,stopDrawing);

/*
Mouse down handler
Begin drawing
*/
function startDrawing(e:MouseEvent):void {
eraserClip.graphics.moveTo(stage.mouseX,stage.mouseY);
doDraw=true;
}

/*
Mouse up handler
Stop drawing
*/
function stopDrawing(e:MouseEvent):void {
doDraw=false;
resumeDrawing = false;
}

/*
Mouse out handler
If user was drawing when they moved mouse off stage, we will need
to resume drawing when they move back onto stage.
*/
function maskOut(e:Event):void {
if (doDraw){
    resumeDrawing = true;
}
}

/*
Mouse over handler
If user's mouse if still down, continue drawing from the point where 
the mouse re-entered the stage.
*/
function maskOver(e:MouseEvent):void {
if (resumeDrawing){
    resumeDrawing = false;
    eraserClip.graphics.moveTo(stage.mouseX,stage.mouseY);
}
}

/*
Mouse move handler
*/
function maskMove(e:MouseEvent):void {
if (doDraw && !resumeDrawing){
    // Draw a line to current mouse position
    eraserClip.graphics.lineTo(stage.mouseX,stage.mouseY);
    // Clear the drawn bitmap by filling it with a transparent color
    drawnBitmapData.fillRect(drawnBitmapData.rect, 0x00000000); 
    // Copy our eraser drawing into the erasable bitmap
    // (This is required to ensure the smooth alpha edges on our eraser are       retained)
    drawnBitmapData.draw(eraserClip , new Matrix(), null, BlendMode.NORMAL);
    // Fill the erasable bitmap with a solid color
    erasableBitmapData.fillRect(erasableBitmapData.rect, 0xFFFFFFFF);
    // Copy the scribble bitmap to our main bitmap, with blendmode set to    ERASE
    // This erases the portion of the mask that has been drawn.
    erasableBitmapData.draw(drawnBitmap, new Matrix(), null, BlendMode.ERASE);
}
// Update after event to ensure no lag
e.updateAfterEvent();
}

/************************RESET BUTTON
**************************/

reset_btn.addEventListener(MouseEvent.CLICK,reset);

function reset(e:Event):void {
eraserClip.graphics.clear();
initEraser();
erasableBitmapData.fillRect(erasableBitmapData.rect, 0xFFFFFFFF);
}

How can I integrate flash, html5 and js to stream webcams in a secure manner in a chat program

This is a high-level question, I'll try to be clear.

I've written a chat system. The backend is node.js and socket.io, serving an html client. That part works nicely. Users come in from a website, which passes a hashed token and a username. This is visible to the logged in user if they view source. When the client connects, the server authenticates these tokens with the originating server before permitting the connection into the chat room. Users could easily 'fake' these tokens by sharing them with each, but then they could also just give each other their login details. So for now, this is intended.

What I need to do next is build webcam functionality. I have a red5 server up and running.

Here is my question. Given the above, what is the best way to integrate actionscript 3 (flash) objects into the chat client securely, i.e. so that the chat objects cannot be misused to broadcast/view cams outside of a legitimate chat session. Of course, I can pass variables to the chat objects when they're embedded, but I have to assume this is visible to the user. I could also have the flash objects communicate directly with the node server, but I'd rather avoid that.

I hope that's clear.

Actionscript3 - Removing entry from Comobox Data Provider (XMLlist) when list entry is disabled

I am modifying code that I did not write and I have minimal experience with Actionscript.

Currently, menu items are greyed out when they are disabled. This is achieved through following classes:

  1. DisabledComboBox (extends ComboBox)
  2. DisabledList (extends List)
  3. DisabledListItemRenderer (extends Label)

Menu constraints are stored in a large XML variable MenuChoiceXML. Each DisabledComboBox refers to an XMLlist which is a subset of MenuChoiceXML as its DataProvider. Each list entry within the XMLlists has an elementsID (integer).

Also within MenuChoiceXML is an XMLlist full menu constraints which are preassembled based on what is available in the database. They use the following form:

  • selecting 15 constrains 5, 12, 23

In other words, selecting 15 in one DisabledComboBox, greys out 5,12, and 23 in other DisabledComboBoxes, and they can't be selected.

Rather than greying them out and disabling the MouseEvent that selects them, I would like to completely remove them from the DataProvider XMLlist.

These are what I believe to be the relevant bits of code:

Item in constraint XMLlist

<Constraints>
        <Cstr choice="DataProvider1" selectedValue="2" constrains="DataProvider2" denies="4,7,12" />
</Constraints>

TotalStateofProgram.as

 public function applyConstraints():void
{


  // before updating menus all constrained menus enable all menu choices, then turn on restricted options

  for each(var menulist:String in constrainedMenuList)
  {
      for each(var xmlentry:XML in MenuChoicesXML.descendants(menulist).MenuItem)
      {
          xmlentry.@enabled=true;
      }
  }

  // Save constraints in XMLlist
  var cstrs:XMLList = MenuChoicesXML.descendants("Constraints").Cstr;

  for each(var cstr:XML in cstrs)
  {
      var choice:String = cstr.@choice;
      var value:String = cstr.@selectedValue;

      // for each constraint - find if it is required constraint selectedValue matches current selection
      var applies:Boolean = (design.getData(choice) == value);
      if(applies)
      {
          var menuname:String = cstr.@constrains;
          var denies:String = cstr.@denies;
          var deniesarray:Array = denies.split(',');

          // Go throught items which are denied by selection
          for(var i:int = 0; i<deniesarray.length;i++) 
          {
              var d:String = deniesarray[i];

              // If something that is to be constrained is currently selected, unselect it from DisabledComboBox
              if(design.getData(menuname) == d) 
                  design.setData(menuname, "0"); // default elementsId for unselected is 0


              // set disable menu choice for this elementsId  
              (MenuChoicesXML.descendants(menuname).MenuItem.(@elementsId == d)).@enabled = "false";

          } 
      }
  }
}

The preceding code resets all constraints, then uses the currently selected menu item to apply constraints to other menu items. The important bit is this line:

(MenuChoicesXML.descendants(menuname).MenuItem.(@elementsId == d)).@enabled = "false";

It appears to be looking up an item in an XMLlist and disabling it. Once disabled, this is seen by the DisabledList and DisabledListItemRenderer where the selected item is turned grey and the MouseEvent attached to it is disabled. (I will post the code which achieves this later, as I'm not 100% it's relevant)

I realize that ComboBox.removeItem() is normally used, but I am unsure how I can look up a ComboBox or DataProvider using the elementsID (as was done above).

Here are some questions I have:

  • Can I look up the ComboBox that has the XMLlist entry in its DataProvider and use ComboBox.removeItem()? How?

  • Can I use the fact that an XMLlist entry is disabled to remove it from the list?

  • Is there another way I'm not considering?

I will work on summarizing the code that greys out the list entry of the DataProvider. I am not sure if it's relevant because the greying out is performed on the text within the list which makes up the DataProvider for the DisabledComboBox, however I want to remove the element from the DisabledCombobox (which seems like less work).

Duplicate and realign

I can create 5 MovieClkips with my code, all 5 MovieClips are in the scene but I can't see them because they are created in the same position. Any solution? Here is the code:

var numOfClips: Number = 5;
var mcArray: Array = new Array();

for (var i = 0; i < numOfClips; i++) {
var newMC: _casa = new _casa();
newMC.ide.text = String(i);
newMC.name = "A" + i;
newMC.index = String(i);
holder.addChild(newMC);
mcArray.push(newMC);
// Any idea here?
newMC.y += 20;
}

AS3 - Why is the font being cleared after setting text of a TextField?

I have the following setup: In Label.fla there is a MovieClip that contains a TextField, which has its class set to src.components.Label. All this class does is set the font in the constructor and then set the text property of the TextField to an empty string (the value of the string doesn't matter for this problem. It can be a non-empty string and have the same result). Like this:

package src.components
{
    import flash.display.MovieClip;
    import flash.text.TextFormat;
    import flash.text.TextField;

    public class Label extends MovieClip
    {
        public var mTextField:TextField;

        public function Label()
        {
            super();

            var tf:TextFormat = new TextFormat("Arial", 34, 0xFFFFFF);
            mTextField.defaultTextFormat = tf;
            mTextField.setTextFormat(tf);

            trace("init before: " + mTextField.getTextFormat().font);
            mTextField.text = "";
            trace("init after: " + mTextField.getTextFormat().font);
        }
    }
}

The label object in Label.fla is set up to export for runtime sharing, which has been copied into MainMenu.fla. A single instance of this label is placed on the stage of MainMenu.fla, and when I run MainMenu.swf the output clearly shows that the font is being set and then immediately cleared just because I'm changing the text property of the TextField.

The output looks like this:

init before: Arial
init after: null

Why would setting the text cause the font to be cleared? This is causing me a lot of problems. The only way I've figured out how to work around this is to do something stupid where I make a copy of the TextFormat object before setting the text, set the text, and then reapply the copied TextFormat to make sure it doesn't change.

I've attached a zip file containing all of the source and compiled files to test this with. FontTest.zip

as3 delete row in datagrid to filter data

Im trying to filter a datagrid by deleting row if value of column is not equal to my input... Below is my code: for(var k:int =0; k

How can I send a binary file from actionScript to .net?

I have a flex program (AS3/Flash) that allows the user to create PNG images of portions of the stage and send them via email. This works swimmingly.

I want to take the same image and send it to the clipboard, but that does not work. So the next best thing is to allow them to send it to their browser, where they can save it to a file.

Here is the code that I am using to do that;

            bmpPanelData.draw(uiPrintObject)
        var baPanel:ByteArray = PNGEnc.encode(bmpPanelData);
//      Clipboard.generalClipboard.clear();
//      var bolClipboard:Boolean = Clipboard.generalClipboard.setData(ClipboardFormats.BITMAP_FORMAT, baPanel, true);
//      trace('bolClipboard=' + bolClipboard);

            var strFileName:String = strPrintObject;
            var strFileExt:String = "png"
            var variables:URLVariables = new URLVariables(); 
            variables.mimeType = "application/octet-stream";
            variables.fileExt = strFileExt;
            baPanel.position = 0;
            var strPanel:String = getBytes(baPanel);
//          var strPanel:String = baPanel.readMultiByte(baPanel.bytesAvailable,"latin1");
            variables.fileContents = escape(strPanel);
            trace('strPanel.length=' + strPanel.length + ' baPanel.length=' + baPanel.length);
            variables.disposition = "Attachment";
            variables.fileName = strFileName;
            var u:URLRequest = new URLRequest( RootDomain + "SendBinaryFile2.aspx");
            u.data = variables; 
            u.method = "POST"; 
            navigateToURL(u,"_blank"); 
    }
    catch (err:Error)
    {
        Alert.show("This Panel cannot be copied to the clipboard. \nSorry for the inconvenience \nError: " + err.errorID,"E-mail not premitted",Alert.OK)
    }

(I left the clipboard stuff commented out in case someone knows how to do that. It is my understanding that you cannot send binary data to the clipboard from Flash, but it works in AIR.)

Since I could not find an AS3 method to convert a binary ByteArray to a string I wrote my own called getBytes. If you know of a method in AS3, please let me know.

    private function getBytes(baArray:ByteArray):String
{
    var strOut:String = "";
    baArray.position = 0;
    var intBASize:int = baArray.bytesAvailable;
    for (var i:int = 0;i < intBASize;i++)
    {
        strOut += String.fromCharCode(baArray.readByte()); 
    }
    return strOut;
}

On the ASPX side I have a file called SendBinaryFile2.aspx that looks like this;

<%@ Page Language="C#" validateRequest="false"%>
<script Runat="Server">

void Page_Load(Object sender, EventArgs e)
{
    string fileExt = Request.Form["fileExt"];
    string mimeType = Request.Form["mimeType"];
    string disposition = Request.Form["disposition"];
    string fileName = Request.Form["fileName"];
    byte [] fileContents = Encoding.ASCII.GetBytes(HttpUtility.UrlDecode(Request.Form["fileContents"]));

    Response.Buffer = true;
    Response.Clear();
    Response.AddHeader("Content-Length", fileContents.Length.ToString());
    Response.ContentType = mimeType;
    Response.AddHeader("Content-Disposition", disposition + "; filename=" + fileName + "." + fileExt);
    Response.BinaryWrite(fileContents);
    Response.Flush();
    Response.Close();
    Response.End();
}
</script>

The results is a file that looks a whole lot like a .PNG file, but is corrupt when it is opened. I have visually compared the file sent via email, and the one sent via this program using VIM, and they look similar, have roughly the same number of characters, begin/end with similar characters.

Help on any of the items defined above is greatly appreciated.

How to display current week number starting on a specific day in AS3?

I'd like display the number of the week but starting on Wednesday. Do you know how could I do that ?

Example : this_week is 13.

and next wednesday the week number will be 14 (on Tuesday it would still be week 13).

Currently my code is this :

function getWeekOfTheYear(d:Date):uint{
    var firstDay:Date = new Date(d.getFullYear(), 0, 1);
    var dayOffset:uint = 9 - firstDay.getDay();
    var firstMonday:Date = new Date(d.getFullYear(), 0, (dayOffset > 7) ? dayOffset - 7 : dayOffset);
    var currentDay:Date = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    var weekNumber:uint = (millisecondsToDays(currentDay.getTime() - firstMonday.getTime()) / 7) + 1;

    return (weekNumber == 0) ? getWeekOfTheYear(new Date(d.getFullYear() - 1, 11, 31)) : weekNumber;
    trace("week number is"+weekNumber);
}

But it's function that I've found on github and calculate the number of the week each Monday...

Thx for your help,

mardi 29 mars 2016

MXML: Default MXML for Different Views

I have the following default mxml configuration.

 <s:ViewNavigatorApplication
    xmlns:fx="http://ift.tt/rYUnH9" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    firstView="Home" 
    creationComplete="init()"
>

Is it possible to have a conditional value for firstView?

I was looking for a way to implement my application in 3 different views for mobile compatibility.
So I would like to create different packages for each views. Is there any workaround for this?

I want to display current week number but starting each Wednesday

I want to display the current week number of the week (I've found a code on internet after searching a lot, for something that should be simple).

But I'd like the week number to change each Wednesday. Is it possible ?

Example : this week is the week 13 and next Wednesday it will be week 14.

Here's my code for the current week number (found on github) :

function getWeekOfTheYear(d:Date):uint{
    var firstDay:Date = new Date(d.getFullYear(), 0, 1);
    var dayOffset:uint = 9 - firstDay.getDay();
    var firstMonday:Date = new Date(d.getFullYear(), 0, (dayOffset > 7) ? dayOffset - 7 : dayOffset);
    var currentDay:Date = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    var weekNumber:uint = (millisecondsToDays(currentDay.getTime() - firstMonday.getTime()) / 7) + 1;

    return (weekNumber == 0) ? getWeekOfTheYear(new Date(d.getFullYear() - 1, 11, 31)) : weekNumber;
        trace("week number is"+weekNumber);

}

Thx

Adobe Air app collapses to a tiny window

I have an Adobe Air 19.0.0.213 application running on Windows 7 Pro 64 bit with a very unusual behaviour. Sometimes the application window gets squished to a very small part of the upper part of the screen for no apparent reason, as you can see in this screenshot. The application is set to start in fullscreen mode. The computer is scheduled to restart everyday. There are no crash logs or any unusual processes running when the issue happens. The application sets the resolution and even if it's not in full-screen mode, it will run at the same resolution (chromeless window) 1080x1920.

Any ideas as to what might be causing this issue?

Thanks.

Number of the current week AS3

I'm trying to have the current week number.

I've found this code :

 function getWeekOfTheYear(d:Date):uint{
    var firstDay:Date = new Date(d.getFullYear(), 0, 1);
    var dayOffset:uint = 9 - firstDay.getDay();
    var firstMonday:Date = new Date(d.getFullYear(), 0, (dayOffset > 7) ? dayOffset - 7 : dayOffset);
    var currentDay:Date = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    var weekNumber:uint = (millisecondsToDays(currentDay.getTime() - firstMonday.getTime()) / 7) + 1;

    return (weekNumber == 0) ? getWeekOfTheYear(new Date(d.getFullYear() - 1, 11, 31)) : weekNumber;
    trace("week number is"+weekNumber);
}

Weird question but, how do I call this function in my code ?

getWeekOfTheYear(//what do I have to put here//);

Actionscript 3, constrain "character" within bounds

So basically I have this point and clik game, the character moves where you click but I'd like to constrain its movements within a certain area, this could be easy if this area was a rectangle but to give a more tridimensional look to the backgroung i need this area to be more complex

see image (blue= background, pink= bounding area (the floor))

any idea?enter image description here

Crystal Report-HTTP Er 500.19 -Internal Server Error-requested page cannot be accessed because the related configuration data for the page is invalid

In my window application i have one crystal report to be generated (crystalReports.aspx) when i'm loading the crystal report it is showing the following error

  HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid.

i have tried lots and lots of different different scenario but still it is coming.., can anyone guide me to resolve my issue will be more helpful to me., thanks in advance

<httpHandlers>
            <add verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
        </httpHandlers>
    </system.web>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <handlers>
            <add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/>
        </handlers>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
    <system.serviceModel>
        <bindings/>
        <client/>
    </system.serviceModel>
  <configSections>
    <sectionGroup name="businessObjects">
      <sectionGroup name="crystalReports">
        <section name="rptBuildProvider" type="CrystalDecisions.Shared.RptBuildProviderHandler, CrystalDecisions.Shared, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304, Custom=null" />
        <section name="crystalReportViewer" type="System.Configuration.NameValueSectionHandler" />
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <businessObjects>
    <crystalReports>
      <rptBuildProvider>
        <add embedRptInResource="true" />
      </rptBuildProvider>
      <crystalReportViewer>
        <add key="ResourceUri" value="/crystalreportviewers13" />
      </crystalReportViewer>
    </crystalReports>
  </businessObjects>


 When i put command on  
<!--<configSections>--to-- </businessObjects>-->

then only my LoadReport() method is get hitting which is inside the page_load method of crystalReports.aspx.cs file.

private void LoadReport()
    {
        ReportDocument = new ReportDocument();


        string reportPath = Path.Combine(ReportFolder, ReportFile);
        ReportDocument.Load(reportPath);

        LoadParameters();

        SetConnection(ReportDocument, connectionString);
        crystalReportViewer.ReportSource = ReportDocument;
    }

but it gives me Script Error-bobj is undefined like that, so i don't know where i made a mistake what i need to do. Please kindly help me to resolve it.

VideoTexture Crashes iPad

I'm running a video texture in Away3d in an Adobe Air app which runs fine on desktop and Android, however on iOS it crashes as soon as it tests for VideoTexture support

I create the video as such

 sphereGeometry = new SphereGeometry(5000, 64, 48);
        panoTexture2DBase = new NativeVideoTexture(Model.config.getAssetUrl(Model.currentScene.video), true, true);

        panoTexture2DBase.addEventListener(NativeVideoTexture.VIDEO_START,function(e:Event =null){setTimeout(onVideoStart,1000)});
        panoTextureMaterial = new TextureMaterial(panoTexture2DBase, false, false, false);

        panoVideoMesh = new Mesh(sphereGeometry, panoTextureMaterial);
        panoVideoMesh.scaleX *= -1;

        panoVideoMesh.rotate(Vector3D.Y_AXIS,-90);

        scene.addChild(panoVideoMesh);
        view.render();

        panoTexture2DBase.player.pause();

And the iPad appears to crash as soon as it plays

            _player.play();

In NativeVideoClass

Does anyone know how to stop the iPad crashing when I try and use VideoTexture or is this doomed to failiure?

lundi 28 mars 2016

Flex, AS3: Bind Width and Height of Component

<forms:InfoClass xmlns:fx="http://ift.tt/rYUnH9" 
             xmlns:s="library://ns.adobe.com/flex/spark" 
             xmlns:forms="ph.com.alliance.iportfolio.forms.*" 
             xmlns:ip="ph.com.alliance.iportfolio.controls.*"    
             styleName="info" width="{mWidth}" height="{mHeight}">

InfoClass.as

[Bindable] protected var mWidth:Number = 400;
[Bindable] protected var mHeight:Number = 200;

I set the container width and height using Bindable, now the problem is that when I change the value of the variables on initParam, it's not reflecting on the container.

Is there anyway that I can change this variable on initParam()?
Tried it, but the width and height are still not reflected, I only get the default values. The thing is all the other binded variables are working just fine. So my question is: Is this even doable? If it is, how can I do this?

Already browsed the net for any workaround, just not sure what to search.. Any ideas?

How to quit using python script pyhook use shortcut keys?

This is , I intend to do a can automatically pasted into the chat window and click with the mouse to send a small script.

However, this script can only run up until after running can stop.

My question is how you can set a shortcut key ( such as F12 ) you can press F12 to stop the script.

Script code is as follows:

# _*_ coding:UTF-8 _*_
import win32api
import win32con
import win32gui
from ctypes import *
import time
import msvcrt
import threading
from time import sleep

stop = 2
def mouse_click(x=None,y=None):
    if not x is None and not y is None:
        mouse_move(x,y)
        time.sleep(0.05)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)     
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)   
def mouse_move(x,y):
    windll.user32.SetCursorPos(x, y)

def baozou():
    global stop
for event in range(1,50):
    mouse_click(1150,665)
    win32api.keybd_event(17,0,0,0)  
    win32api.keybd_event(86,0,0,0)  
    win32api.keybd_event(86,0,win32con.KEYEVENTF_KEYUP,0) 
    win32api.keybd_event(17,0,win32con.KEYEVENTF_KEYUP,0) 
    mouse_click(1272,669)
    time.sleep(0.1)
    if stop == 1:
        sys.exit()

def Break():
    global stop
    if ord(msvcrt.getch()) == 123:
        stop = 1

if __name__ == "__main__":
    t = threading.Thread(target = baozou)
    f = threading.Thread(target = Break)
    t.start()
    f.start()

please give me a hand!

Scrubber Probleme : air app

I have created a scrubber for streaming video (flash professional cs6) .It work with the short video . but with the longest don't work . Any idea to make the seek() method go to specific time without need to download the full video.

thanks:

var _duration:Number;
var _scrubbing:Boolean;

//-------------------- download and add the video ----------------------------//

var nC:NetConnection = new NetConnection ();
nC.connect(null);

var ns:NetStream = new NetStream(nC);
ns.play("")

var vid:Video = new Video();
vid.attachNetStream(ns);
addChild(vid);


vid.width = v_container.width;
vid.height = v_container.height;
vid.smoothing = true;

var client:Object = new Object(); 
client.onMetaData = onMetaData; 
ns.client = client;             


function onMetaData(metaData:Object):void
{
    _duration = metaData.duration;  
}

//--------------------  creat playhead and lesten to mouse event--------------------------//

drag.addEventListener(MouseEvent.MOUSE_DOWN,drag_To_Position);
stage.addEventListener(MouseEvent.MOUSE_UP,_stop_drag_To_Position);
addEventListener(Event.ENTER_FRAME,calculate_position);

function drag_To_Position(e:MouseEvent):void
{
    drag.startDrag(false,new Rectangle(bar.x,bar.y,bar.width - drag.width,0));
    _scrubbing = true;
}

//---------------------------------------------------------------//

function _stop_drag_To_Position(e:MouseEvent):void
{
    drag.stopDrag();
    _scrubbing = false ;

}

//----------------- seek method & specific time ------------------//

function calculate_position(e:Event):void
{

    if ( _duration > 0 )
    {
        if ( _scrubbing == true )
        {
            ns.seek( _duration * drag.x / bar.width );
            var posi:Number = Math.floor((bar.x - drag.x) / (drag.width  - bar.width) * 100 );
            pro.gotoAndStop(posi);
        }
        else
        {
            var seckto:Number = Math.floor((bar.x - drag.x) / (drag.width  - bar.width) * 100 );
            drag.x = ns.time / _duration * bar.width ; 
            pro.gotoAndStop(seckto)
        }
    }
}

Best approach for desktop -> mobile?

Im building an AIR desktop app. I have a bunch of information that id like to get to a cell phone so it can be accessed on-the-go rather than actually loading the app on your phone. What is the best approach? E-mail it? Build a seperate mobile app that can load a xml file with saved data? Any help would be appreciated!

Need help on making a package which moves the player and creates gravity in as3

hello I need help on creating a package which can move a player in a platform game and which can also create gravity

Flash AS3 print specific position

I'd like to print my object(movie clip) in action script 3. However this object will be printing with changing position at A4, B5.

What I mean is that the object must be positioned 100px from the top and center horizontal in A4 document size.

The object have to be located 150px from the top and center horizontal as well At B5 document size.

But how can I calculate the unit of printing such as px, cm? or mm? or point?. And is this possible that I mentioned above set the object specific location according to paper size? e.g. 150px from the top or 100px from the top?

Thank you.

Flash Builder. Create dynamic mxml package instance

so, I just beginning flash builder. to the point

my app package structure:

index.mxml (default) <s:application/>
  [main]
    signin.mxml <s:form/>
    dashboard.mxml <s:group/>
      [content]
        home.mxml
        data_a.mxml
        data_b.mxml
        post.mxml
        and-many-more-mxml-file.mxml
        etc.mxml

index.mxml work as (something like) front controller. that will only load main package component (signin,dashboard).

index.mxml fx:script:

import main.signin;
import main.dashboard;

public var m_signin:main.signin = new signin();
public var m_dashboard:main.dashboard = new dashboard();

private function app_ready():void { //creationComplete
    //...service to check session...
    if(is_signed) {
        addElement(m_dashboard);
    } else {
        addElement(m_signin);
    }
}

success.

we assume that user is signed. then from main/dashboard.mxml I want to load package from main.content.* that defined in array.

main/dashboard.mxml fx:script:

protected var dashboard_content:Object = {};
protected var dashboard_content_list:Array = [
    ['home','Home Admin'],
    ['user_a','User Data A'],
    ['user_b','User Data B']
    //many more.
];
for (var i:int = 0; i < dashboard_content_list.length; i++) {
    var content_class:Class = Class(getDefinitionByName('main.content.'+dashboard_content_list[i][0]));
    var content_obj:Object = new content_class();
    dashboard_content[dashboard_content_list[i][0]] = content_obj; //for refference each component
}

each array from dashboard_content_list explain:

0: package suffix that i want to load (ex: `main.content.home`).
1: button label (for each content).

but the loop is still not working, always ReferenceError: Error #1065.

so what I want todo is: load main.content.* package class and save it on Object in main/dashboard.mxml.

some of my refference (but still not working.): http://ift.tt/1XXOFfU http://ift.tt/22H29U7 http://ift.tt/1XXOFfV Instantiate a class from a string in ActionScript 3 Dynamically Creating Flex Components In ActionScript AS3: Cast Variable as Dynamic Type http://ift.tt/1XXOFfZ http://ift.tt/22H29U8 http://ift.tt/1XXOFg1

sorry for by bad english :) thanks.

Why stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, true); don't work?

I want to listen to stage for keyboard event, and I want to catch an event directly when it appears (not in bubbling or target). Why can't I do this?

How to write my first smartfoxserver Extension

How to write my first smartfoxserver Extension

Exception in thread "main" java.lang.NoClassDefFoundError: org/joda/time/ReadablePartial at com.smartfoxserver.v2.Main.main(Main.java:21) Caused by: java.lang.ClassNotFoundException: org.joda.time.ReadablePartial at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more

Please help me solve this error. Also I'm writing my extension in eclipse.

AS3 display Text from XML file on dynamic textfield

im trying to have my dynamic textfield on my stage display the quantity data from my xml file

format of my xml file

<?xml version="1.0"?>
<root>
    <data>
        <item>
            <quantity>4470</quantity>
            <avg_sentiment_score>3.4596106511524</avg_sentiment_score>
            <total_votes>1</total_votes></item>
    </data>
    <errors></errors>
</root>

my as3 code

var myXML:XML;
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("summaries.xml"));
myLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void {
myXML = new XML(e.target.data);
trace(myXML.*);
quantity_txt = xml.quantity.text()[0];
}

any help would be greatly appreciated

Thanks!

dimanche 27 mars 2016

Playing a video with flex, AS3

I am currently trying to make a game on flex and one of the problems I ran in to is how to play a short animation at the beginning. This is what I have so far:

Game.mxml

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://ift.tt/1aBfKeP"
    name="Game"
    backgroundColor="#000000"
    horizontalAlign="center"
    creationComplete="Init();"
    enterFrame="UpdateFrame();"
    paddingLeft="0"
    paddingTop="0"
    paddingBottom="0"
    paddingRight="0"
    width="800" height="600">

  <mx:Script>
  <![CDATA[
    include "Game.as";
  ]]>
  </mx:Script>

  <mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%" mouseDown="MouseDown(event)" mouseUp="MouseUp(event)" mouseMove="MouseMoved(event)"/>
</mx:Application>

and Game.as

import flash.display.*; 
import flash.events.*;
import flash.external.ExternalInterface; 
import mx.events.*;
import mx.controls.*;

[Embed(source="MyVideoClip.flv")] private var MyVideoClip:Class;

public function Init():void
{   
    var MyVideo:Video = new Video(800, 600);
    addChild(MyVideo);
    var qNetConnection:NetConnection = new NetConnection();
    qNetConnection.connect(null);
    var qNetStream:NetStream = new NetStream(qNetConnection);
    MyVideo.attachNetStream(qNetStream);
    qNetStream.client = new Object();
    qNetStream.play(MyVideoClip);
}

private function UpdateFrame():void
{

}

private function MouseDown(event:MouseEvent):void   
{   

}   

private function MouseUp(event:MouseEvent):void     
{

}

private function MouseMoved(event:MouseEvent):void  
{

}

I am rather new to Flex and AS3 so most of this code was ripped off web tutorials. Whenever I try to compile it I get: 'Error: 'MyVideoClip.flv' does no have a recongnized extention, and a mimeType was not provided. Error: unable to transcode 'MyVideoClip.flv''

If I remove the 'embed' line and replace MyVideoClip with "MyVideoClip.flv" in the play() function, the code compiles with no errors, but when I open the SWF all I get is a black screen. What am I doing terribly wrong?

Thanks in advance!!

Assets class calls not working

I'm making a class that embeds all the assets I need, icons, fonts, images, etc; I took it from Adrian's answer here.

This is pretty much the structure it has:

public class Assets 
{
    [Embed(source = "../assets/images/imageBG.png")]
    private static var imageBG:Class;

    [Bindable]
    private var imageName:Class;//There wasn't a ";" here, no error but I added it just in case

    public static function setImage(newImageName:Class):void
    {
        imageName = newImageName:Class;
    }
}

And I'm supposed to use something like this from a different class on the same package to call the asset I need (although it should work in any other class)

    image = new Assets.setImage(imageBG) as Bitmap;

As it is, it trows "Label must be a simple identifier."

if I change

imageName = newImageName:Class;

to

imageName = newImageName; //The "Class" part was pointed as the error

it trows this "Access of undefined property imageName."

when is called on the function and this from wherever it's called

"Method cannot be used as a constructor."

pointed right after the "Assets." part.

I'm obviously doing something wrong but I don't know what it is, if anyone can help please.

Also, is OK if I ask how can I change things so that I can call the asset passing it's name as a string? or should I make another question?

Thanks in advance.

Assistance converting AS2 to AS3

Just need a quick hand converting AS2 to AS3. I have never learnt AS2 so could really use some help I followed a tutorial to create a colouring book and it turns out it was all in AS2 my assignment is to follow a tutorial then expand on it. The tutorial I followed is~: http://ift.tt/1Rvg5WM

If someone can help me change the code into AS3 it would be incredible!

Movieclip X/Y Values don't update in ScrollPane?

I finally signed up as i'm constantly using this forum now. I have some movieclip positioned in a scrollpane. A tooltip appears on mouseOver of the movieclips and positions itself based on the x/y of the movieclip. The x/y coordinates don't change when the scrollpane is scrolled? Any ideas?

Using a bug-fixed Apache component with Flex 4.6?

I think I know the answer to this but thought I would put out the question, since I'm not a Flex "super user" in any sense.

Situation: I've inherited a large legacy enterprise project done in Flex 4.6. For some small feature additions I needed to use the mx PopUpMenuButton. After some development time I started seeing a reproducible bug. Didn't see any reporting of it on the web until I found this Apache Flex bug report:abnormal focus behavior in popup ultimiately causes unhandled exception which accurately describes it and states that it has been fixed.

Question: I can't update to Apache Flex 4.12+ – my project is too large and there would be just too much testing required. Is there any way I can use the PopUpMenuButton from 4.12+ as a custom component, bringing in whatever dependencies there are with it?

My guess is: no – that the dependencies are too extensive for this to be practical and would need too much refactoring to avoid namespace collision. Thoughts? Or alternatives to the PopUpMenuButton?

Restrict text field to mathematical expressions - Convert String to mathematical expression

How can I restrict the input of a TextFieldsuch that it can only contain mathematical expressions?

Accepted inputs would be:

"3+5"

"-5 + 6"

"3/2(6*4)"

"6--5"

"+5-3"

etc..

And rejected inputs would be:

"5+++3"

"6(7)"

"6-6-+-7"

and so on.

Basically; the syntax I want it to be restricted to is the kind of syntax that programming languages normally use for evaluating mathematical expressions, kinda like the syntax input you'd expect from your everyday calculator.

I'm making a program in which I want the user to be able to input numbers and/or calculations into a text box, instead of having to use a calculator to do it and then arduously type out a number with 7 decimal places.

I've done a little look around and I've seen a lot of stuff involving Regex, postfix, BNF, and the like. A lot of it looked very complicated, too complex for my understanding, and none of it had anything to do with AS3.

However, I've had a thought about making this problem a whole lot simpler by just converting the string into a mathematical expression that AS3 can understand, and let Flash handle the errors using try catch, but I don't know how to do that either (Number("3+5")resulted to NaN).

I'm currently restricting text input to just numbers using Event.CHANGE, like this:

function Restrict(event:Event):void
        {

            if (event.currentTarget.text.indexOf(".") == -1)
            {
                event.currentTarget.restrict = "0-9.";
            }
            else
            {
                event.currentTarget.restrict = "0-9";

            }
        }

and it's seemed to work well so far.

I intend to implement this new restriction in this manner, but if there is a much more efficient way of restricting text input, please feel free to include it in a response.

Just to reiterate for clarity, I am asking how to implement functionality that will enable someone to input a mathematical expression into a TextField, and the program will register that input as an expression and calculate it.

Thanks for reading.

Uncaught TypeError: this.EventDispatcher_initialize is not a function createjs error

i am following a famous book "beginning html5 game development with createjs.pdf " Apress Publication . Anyhow when i run the codes i get error in my browser console : i updated my createjs hosted lib to latest version gs skinner github i found p.initialize =function is deprecated . i am not a good programmer. is there any way so that i can fix the error and run the codes of this book. thanks

Uncaught TypeError: this.EventDispatcher_initialize is not a function AssetManager.js:34 Uncaught TypeError: here i pasted few lines for 34 to last of function

 p.initialize = function () {
        this.EventDispatcher_initialize();
        this.loadManifest = [
            {id:this.EXPLOSION, src:this.assetsPath + 'explosion.mp3'},
            {id:this.SOUNDTRACK, src:this.assetsPath + 'dreamRaid1.mp3'},
            {id:this.GAME_SPRITES_DATA, src:this.assetsPath + 'all.json'},
            {id:this.GAME_SPRITES, src:this.assetsPath + 'all.png'}
        ];
    }

Need to remake c++ to as3

I need help in changing c++ code to as3 one. I am trying to make this tutorial work for as3.

The c++ code looks like this:

b2Vec2 getTrajectoryPoint( b2Vec2& startingPosition, b2Vec2& startingVelocity, float n ) {      
  float t = 1 / 60.0f;
  b2Vec2 stepVelocity = t * startingVelocity; 
  b2Vec2 stepGravity = t * t * m_world->GetGravity();

  return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity;  }

For now I don't clearly understand how to work with float in as3.

Thanks for your attention and help.

Actionscript 3 Password Verifier Doesn't Match Passwords

I'm working on an flash password verification project where a user types in a password that's 6 to 10 characters and must contain one uppercase, one lowercase, and one number.

When I test the program and type in a password I get the "Passwords DID NOT MATCH. Try again." in the feedback_txt field.

I have two functions that are called by the Submit button’s event handler: Same() and PasswordApproved(). The Same function verifies the password was entered both times. The PasswordApproved function verifies that the password meets specified standards.

I was giving a tip to use CharCodeAt to help with the PasswordApproved part, but I can't seem to figure out how to do that.

Here's part of the Code:

submit_btn.addEventListener(MouseEvent.CLICK,Submit);
function Submit(e:MouseEvent):void {
var pass1:String = password1_txt.text;
var pass2:String = password2_txt.text;
if (Same(pass1,pass2) == true) {
if (PasswordApproved(pass1) == true)  {
        feedback_txt.text = "Your password was APPROVED."
        feedback_txt.textColor = 0x00FF00;

This is what I have for the functions (I think this is the reason why it's not working. I'm not writing it correctly? or it's just wrong) :

function Same(pass1,pass2:String):void {
var pass1:String = password1_txt.text;
var pass2:String = password2_txt.text;
}


function PasswordApproved(pass1:String):String {
var pass1:String = "abchefghjkmnpqrstuvwxyzQWERTYUIOPLKJHGFDSAZXCVBNM0123456789";
var i:Number = 0;
var pass:String = "";
var nLength:Number = pass1.length;
var length:Number = 10
while(i<=length) 
{
    var num:Number = Math.round(Math.random() * nLength);
    pass += pass1.charCodeAt(num);
    i++;
}
return pass;
}

play in loop the 2nd video after the first ends (actionscript 2)

I have done a project of a video playlist (actionscript2) in Flash CS3 using XML but I have a video "clip1.flv" that it should appear to the end of each video that is played but also this "clip1.flv" should play in loop until another video is selected from the playlist.

At the moment I have the following code:

var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
theVideo.attachVideo(ns);
var vlist:XML = new XML();
vlist.ignoreWhite = true;
vlist.onLoad = function() {
var videos:Array = this.firstChild.childNodes;
for (i=0;i<videos.length;i++) {
videoList.addItem(videos[i].attributes.desc,videos[i].attributes.url);
}   

 ns.play(videoList.getItemAt(0).data);
videoList.selectedIndex=0;  
}
var vidList:Object = new Object();
vidList.change = function() {
ns.play(videoList.getItemAt(videoList.selectedIndex).data);
}
videoList.addEventListener("change",vidList);
vlist.load("videos.xml");       

////////////// resume play ////////////////////////////
playButton.onRelease = function() {
    ns.pause();
}
/////////// loading bar //////////////
var videoInterval = setInterval(videoStatus,100);
var amountLoaded:Number;
var duration:Number; 
ns["onMetaData"] = function(obj) {
duration = obj.duration;
}
function videoStatus() {
amountLoaded = ns.bytesLoaded / ns.bytesTotal;
loader.loadbar.width = amountLoaded * 285.5;
loader.scrub._x = ns.time / duration * 280;
}

any idea to solve my problem ?

How to put to sleep the non-visible part of your map?

I'm creating a level modifying slightly the destructible terrain class from here:

http://ift.tt/1MKEUMh

Instead of using PerlinNoise to create a random map, I input my own bitmapdata. When the size of the terrain is the size of the stage, the performance is just fine, however when I put there a 4096x4096 custom bitmap, I get less than 25 fps, which is expected since it has a lot more of area to calculate.

I assume this has a workaround/best practice, like putting to sleep the area of the level you don't see, maybe passing a AABB region of the space that shouldn't count towards calculation for example, but no idea, I'm guesstimating.

If anyone knows what would be a good approach, let me know, thanks.

AS3 query: How to overide all functions regarding keyboard and mouse

I'm not from the field of software engineering but I need something to be resolved.

I have an flash program which uses Actionscript 3, the problem is whenever I open the program the right mouse feature is disabled and the cut, copy, paste(Ctrl+x,c,v) feature is also not working. For me the most important feature is the cut, copy, paste and I don't know a single thing about coding.So could someone please take a look at it and tell me how to fix this.

I desperately need help regarding this issue. I thank you in advance for helping me.

Here is the link to the exe file

Just Download the editor from http://ift.tt/25qSaBe Password: MF Notepad Password is case sensitive.

Debugging of Flash file and actionscript (Simple)

recently I am making a website HTML, and created a small Flash file, whereby if I hover a mouse over the movie clip symbol, alpha value will increase. Likewise if I remove the mouse, the alpha value will decrease to a set value. However, when I used Test Movie, I get such a warning "Frame numbers in EaselJS start at 0 instead of 1. For example, this affects gotoAndStop and gotoAndPlay calls.(7)", also, my endproduct is simply a blank white screen in Google Chrome. It is a really simple file, so it will not take much of your time, but I am unable to solve it. Thanks in advance! The link for the file is here[http://ift.tt/1Sev0Eg]

Flash AS3 making a mask with movie clip

I want to apply mask effect into movie clip.

I made a movie clip that was divided 3 areas.

parent movie clip name is "box"

1 area name(Child box) = "m0" as MovieClip
2 area name(Child box) = "m1" as MovieClip
3 area name(Child box) = "m2" as MovieClip

I've converted image file to movie clip named "pic.."

1 photo file(Located at Stage) = "pic0" as MovieClip
2 photo file(Located at Stage) = "pic1" as MovieClip
3 photo file(Located at Stage) = "pic2" as MovieClip

I'd like to apply masking effect dynamically.

I have no idea of this, Can you give an advice a little bit?

var btn:MovieClip = this["btn"] as MovieClip;
btn.addEventListener(MouseEvent.CLICK, goon);

function goon(Event:MouseEvent):void{
    var pic0:MovieClip = this["pic0"] as MovieClip;
    var pic1:MovieClip = this["pic1"] as MovieClip;
    var pic2:MovieClip = this["pic2"] as MovieClip;
    var box:MovieClip = this["box"] as MovieClip;
    trace(box.m0.x + " , " + box.m0.y);

    //box.addChild(mc0);
    box["m0"].mask = box["m0"];
    box["m0"].addChild(pic0);
    pic0.x = 0;
    pic0.y = 0;

}

However it's not working at all. What should i do?

samedi 26 mars 2016

setting textfield vertical alignment, AS3

textFormat.align = "center";

This, but a vertical equivalent please? Because of my experience with HTML I have tried

textFormat.valign = "middle";

But it does not work

Keep on moving towards point

So I'm trying to make a basic interactive pet game in AS3 using flashpunk due to it's ability to use sprite sheets. I've got the animations down (idle and walking) and moving the "pet", but I have ran into a problem.

With my current system, I have to hold down click to keep on moving the pet towards the mouse, but I want it to move to the position where the mouse was when I clicked rather than having to hold it down.

Here's my code(the checking if mouse is released part is just so it can stop the animation):

    override public function update():void
    {
        trace(FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY))
        if (Input.mouseDown)
        {
            move(FP.world.mouseX, FP.world.mouseY)
            Moving = true
        }
        if (Input.mouseReleased)
        {
            Moving = false
        }
        if(Moving && FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) < 130 && FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) > 20)
        {
            sprRocket.play("WalkU")
        }
        if (Moving && FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) < 350 && FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) > 225)
        {
            sprRocket.play("WalkD")
        }
        if (!Moving)
        {
            sprRocket.play("Idle")
        }
        //if (FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) < 130 && FP.angle(sprRocket.x, sprRocket.y, FP.world.mouseX, FP.world.mouseY) > 20)
        //{
            //sprRocket.play("WalkU")
        //}
        //else
        //{
            //sprRocket.play("IdleD")
        //}
    }

    public function move(x:int,y:int):void
    {
        var angle:int = FP.angle(sprRocket.x, sprRocket.y, x, y)
        sprRocket.x += 100 * Math.cos(angle * FP.RAD) * FP.elapsed
        sprRocket.y += 100 * Math.sin(angle * FP.RAD) * FP.elapsed
        trace(angle)
    }

Get size of frame in sprite sheet

I'm using flashpunk and I'm trying to get a sprite sheet working.

The sprite sheet I'm using is Rocket from Dragon Quest Heroes Rocket Slime

Since I only need a part of the animation, I cut his animation out of the sprite sheet which is the 8 columns x 5 rows animation in the top left of the sheet. The size of it cut out is 215x146

This is the problem I'm having (I assume this is caused by not having the correct frame size of the sprites in the sheet)

I was told on the flashpunk forums to divide the height of the image by the number of rows in the animation and the same for the width and columns. But that caused what is shown in the problem.

Here's my code for the sprite right now:

 public class Rocket extends Entity
    {

    [Embed(source = "../img/Rocket.png")]
    public var RocketImg:Class;

public var sprRocket:Spritemap = new Spritemap(RocketImg, 43,18.25);
    public function Rocket() 
    {
        sprRocket.add("walk",[0,1,2,3,4,5,6,7],10,true)
        graphic = sprRocket
        sprRocket.play("walk", false);
        sprRocket.y = 100
    }
    override public function update():void
    {
    }
}

ActionScript 3 Error: 1083: Syntax error: package is unexpected

Hi I'm currently learning how to use Flash so I'm creating a colouring book as a project I'm just having trouble with my code though. The Code I've written is:

PrevBtn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_14);

function fl_ClickToGoToAndStopAtFrame_14(event:MouseEvent):void
 {
    gotoAndStop(40);
 }

    HomeBtn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_11);

    function fl_ClickToGoToAndStopAtFrame_11(event:MouseEvent):void
    {
    gotoAndStop(10);
    }


    NextBtn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_13);

    function fl_ClickToGoToAndStopAtFrame_13(event:MouseEvent):void
    {
    gotoAndStop(20);
    }



    HelpBtn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_31);

    function fl_ClickToGoToAndStopAtFrame_31(event:MouseEvent):void
    {
    gotoAndStop(45);
    } 


package {
    import flash.display.Sprite;
    import flash.geom.ColorTransform;
    import flash.events.MouseEvent;
    public class coloring extends Sprite {
        public var Design1:Design1 = new Design1();
        public var palette:palette_mc;
        public var pal_color:ColorTransform;
        public var colors:Array=new Array(0x000000,0xFFFFFF,0xFF0000,0xFF4040,0x333399,

                                      0x99CCCC,0xFFCC00,0xFFFF66,0x33CC00,0x99FF66,
                                      0x660099,0x9933FF,0xFF8000,0xFF9966,0xFF0099,
                                      0xFF99CC,0x0099CC,0x6699CC,0x666666,0xCCCCCC,
                                      0x003366,0x000033,0x99CC99,0x4E9A4E,0x9966FF,
                                      0x990066);
    public var current_color:int=0;
    public function coloring():void {
        addChild(Design1);
        Design1.addEventListener(MouseEvent.CLICK,on_Design1_click);
        for (var i:int=0; i<26; i++) {
            palette = new palette_mc();
            pal_color=palette.transform.colorTransform;
            pal_color.color=colors[i];
            palette.transform.colorTransform=pal_color;
            palette.x=40+i*60;
            palette.y=300;
            palette.ind=i;
            addChild(palette);
            palette.addEventListener(MouseEvent.CLICK,on_palette_click);
        }
    }
    public function on_palette_click(e:MouseEvent):void {
        var palette_clicked:palette_mc=e.currentTarget as palette_mc;
        current_color=palette_clicked.ind;
    }
    public function on_Design1_click(e:MouseEvent):void {
        for (var i:int = 0; i < Design1.numChildren; i++) {
            if (Design1.getChildAt(i).hitTestPoint(mouseX,mouseY,true)) {
                pal_color=Design1.getChildAt(i).transform.colorTransform;
                pal_color.color=colors[current_color];
                Design1.getChildAt(i).transform.colorTransform=pal_color;
            }
        }
    }
}
            }

Any help would be majorly appreciated. Thanks in advance!

Error 1120: Access of Undefined Property

I have on shape named sss in the stage in frame one and in layer 1. but why is it undefined? error:

Scene 1, Layer 'Layer 3', Frame 1, Line 5   1120: Access of undefined property sss.

code:

sss.stop();

startt.onPress= function (){

    sss.start();
    }

Convert AS3 code to C#

I converting my application from AS3 to C# but I don't know how I can convert this code block:

function drawCubicBezier(_arg1: Graphics, _arg2: int, _arg3: int, _arg4: int, _arg5: int, _arg6: int, _arg7: int, _arg8: int, _arg9: int): void {
        var _local18: Number;
        var _local19: Number;
        var _local21: Number;
        var _local22: Number;
        var _local10: int = (Math.abs(((_arg8 - _arg2) * (_arg8 - _arg2))) + Math.abs(((_arg9 - _arg3) * (_arg9 - _arg3))));
        var lineColor: Number = Math.max(0.1, (1 - (_local10 / 2000)));
        var _local12: int = ((_arg8 + (3 * (_arg4 - _arg6))) - _arg2);
        var _local13: int = ((_arg9 + (3 * (_arg5 - _arg7))) - _arg3);
        var _local14: int = (3 * ((_arg2 - (2 * _arg4)) + _arg6));
        var _local15: int = (3 * ((_arg3 - (2 * _arg5)) + _arg7));
        var _local16: int = (3 * (_arg4 - _arg2));
        var _local17: int = (3 * (_arg5 - _arg3));
        var _local20: Number = lineColor;
        while (_local20 < 1) {
            _local21 = (_local20 * _local20);
            _local22 = (_local21 * _local20);
            _local18 = ((((_local22 * _local12) + (_local21 * _local14)) + (_local20 * _local16)) + _arg2);
            _local19 = ((((_local22 * _local13) + (_local21 * _local15)) + (_local20 * _local17)) + _arg3);
            _arg1.lineTo(_local18, _local19);
            _local20 = (_local20 + lineColor);
        };
        _arg1.lineTo(_arg8, _arg9);
    }

and

function drawVector(graphic: Graphics, vectorData: String, LocationX: int, LocationY: int, colori: uint = 0): void {
        var _local8: int;
        var _local9: int;
        var _local10: int;
        var _local12: int;
        var _local13: int;
        var _local14: int;
        var _local15: int;
        var _local16: int;
        var _local17: int;
        var _local18: int;
        var _local19: Array;
        var _local6: int;
        var _local7: int = vectorData.length;
        var lineColor: uint = colori;
        while (_local6 < _local7) {
            switch (vectorData.charAt(_local6)) {
                case "B":
                    graphic.beginFill(lineColor);
                    break;
                case "F":
                    graphic.endFill();
                    break;
                case "S":
                    lineColor = uint("0x" + vectorData.substr((_local6 + 1), 6));
                    _local6 = (_local6 + 6);

                    break;
                case "M":
                    _local8 = parseInt(vectorData.substr((_local6 + 1), 8), 16);
                    _local9 = (_local8 >> 16);
                    _local10 = (_local8 & 0xFFFF);
                    graphic.moveTo((_local9 + LocationX), (_local10 + LocationY));
                    _local6 = (_local6 + 8);
                    break;
                case "L":
                    _local8 = parseInt(vectorData.substr((_local6 + 1), 8), 16);
                    _local9 = (_local8 >> 16);
                    _local10 = (_local8 & 0xFFFF);
                    graphic.lineTo((_local9 + LocationX), (_local10 + LocationY));
                    _local6 = (_local6 + 8);
                    break;
                case "C":
                    _local8 = parseInt(vectorData.substr((_local6 + 1), 8), 16);
                    _local12 = (_local8 >> 16);
                    _local13 = (_local8 & 0xFFFF);
                    _local8 = parseInt(vectorData.substr((_local6 + 9), 8), 16);
                    _local14 = (_local8 >> 16);
                    _local15 = (_local8 & 0xFFFF);
                    _local8 = parseInt(vectorData.substr((_local6 + 17), 8), 16);
                    _local16 = (_local8 >> 16);
                    _local17 = (_local8 & 0xFFFF);
                    drawCubicBezier(graphic, (_local9 + LocationX), (_local10 + LocationY), (_local12 + LocationX), (_local13 + LocationY), (_local14 + LocationX), (_local15 + LocationY), (_local16 + LocationX), (_local17 + LocationY));
                    _local9 = _local16;
                    _local10 = _local17;
                    _local6 = (_local6 + 24);
                    break;
                case "G":
                    _local18 = ((vectorData.indexOf("!", (_local6 + 1)) - _local6) - 1);
                    _local19 = vectorData.substr((_local6 + 1), _local18).split("#");
                    _local6 = (_local6 + _local18);
                    drawVector(graphic, vectorData.substr(_local19[0], _local19[1]), parseInt(_local19[2]), parseInt(_local19[3]), lineColor);
                    break;
            };
            _local6++;
        };
    }

I converted part of this code to C# but I don't know how I can convert lineTo and moveTo to C#.. This code block draws vectordata from file to AS3 graphic..

circle progress bar for player

Maybe the problem and simple, but not for me, with trigonometry was always tight. This should be a round progress bar for the player. There is a circle, you need to calculate the angle from 0 to a point where the touch / click occurred.

I found this:

var degr:Number = (getAngle(centerX, centerY, touchX, touchY) * 180 / Math.PI);

private function getAngle (x1:Number, y1:Number, x2:Number, y2:Number):Number
{
    var dx:Number = x2 - x1;
    var dy:Number = y2 - y1;
    return Math.atan2(dy,dx);
}

but it outputs on one side of from 0 to 180, on the other between -180 and 0. need from 0 to 360.

Please share with us his thoughts. Who can faced with, can anyone have a solution ready, I will be grateful)

vendredi 25 mars 2016

How to refer to a symbol from inside a document class?

So here I have created a MovieClip symbol of the name devTextMC. I have linked my .fla file to a (document) class of the name supportForce and I execute all the code from it. However, I am unable to make any reference to the devTextMC from inside supportForce. For example-

addChild(devTextMC);

Gives an error 1067: Implicit coercion of a value of type Class to an unrelated type flash.display:DisplayObject. I have a slight idea of what to do here, that is, to declare a variable or something, but I'm not sure.

I am very sorry if the question is unimportant, but I need it clarified. Thanks in advance.

Using Proguard with AIR SDK Mobile

I'm using FlashDevelop as IDE to create Air mobile apps, but have not encountered and seen any documentation or article pertaining to enabling or setting up Proguard with AIR SDK.

Generally APKs in Flex/Air SDK are created by running the bat files generated along with the creation of a project. Apparently, you don't see any build.xml or properties file.

Playing a video with Flex, ActionScript 3.0 - no UI

I am currently trying to make a game on flex and one of the problems I ran in to is how to play a short animation at the beginning. I found plenty of examples on the web about how to may it from MXML and how to add UI - my goal is to just play it from an AS file with no UI (and, if possible, to embed it into the SWF).

I am quite new to flex so sorry if this question is stupid...

Thanks in advance for any help!

Restart after nothing happend for certain time

I would like to set a function in every frame, that restarts the Flash-Application after nothing happend (MouseMove) for 30 Seconds. I am new to AS3 and would be happy for any idea and maybe some snippets.

Can you help me

How to get the week number of month AS3 (Actionscript 3)

How would I get the week number in a given month of a Date?

I can retrieve the week number in a year w/ getWeekOfTheYear (d:Date) but a calculation based around that will prove difficult - any help is greatly appreciated

Instead of using a hex code for a color, make it transparent [AS3]

So lets say I have some code in as3, and it requires a given color (Current one is 0x701100 for example) but instead of giving it a hex color code, I want it to be transparent, aka no color, aka see through, you get what I mean. This is basically the line of code that determines what color it is: super(0x701100, 0x8D1500); and well the 0x8D1500 represents some other things color, but all I want is the 0x701100 to be transparent/not show.

Player centred compass

I'm new to programming and currently trying to make a top down delivery service game, now I've done quite a bit of searching but can't seem to find anything that can help. I need a player centred compass like the old gta1/gta2 style mission/objectives where it can have a few markers on the map and a few arrows on the the player showing the direction, any help would be very much appreciated.

jeudi 24 mars 2016

Flex Sort is sorting where nothing should be sorted (in an ArrayCollection)

I try to sort an arrayCollection with this Sort:

    private function sortArray(questions:ArrayCollection):void
    {
        questions.sort = new Sort();
        questions.sort.fields = [new SortField("rank")];
        questions.sort.compareFunction = rankFunction;
        questions.refresh();
    }

    private function rankFunction(a:int, b:int, array:Array = null):int
    {
        if(a == b)
        {
            return 0;
        }
        if(a>b)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }

There are 23 Objects and all have the rank = 0

I expected that nothing will be changed but after the refresh the items at postion 0 and 11 of the ArrayCollection swapped their position.

In the rankFunction, there is always returned 0.

Can anyone tell me what is going wrong here?

adding X amount of addChild per maxvalue in loop

The assignment is the spawn several light and dark feathers according to score points from a quiz. The light feathers symbolize the correct points (light_feather), and the dark feather are the incorrect points (dark_feather) (Each are being tracked). All the feathers are supposed to line up on one line, meaning first light feathers, followed by the dark feathers. I got the quiz dynamics figured out, and the function I have posted here is only for when they press end quiz.

var light_feather:LightFeather = new LightFeather();
var dark_feather:DarkFeather = new DarkFeather();

var good_answers:uint = 0;
var bad_answers:uint = 0;

function avsluttFunc (evt:MouseEvent) 
{   
    var sum_LightFeatherX:Number = 0;
    for (var i = 0; i < good_answers; i++) {
        addChild(light_feather);
        light_feather.x += 12 + (i*16);
        light_feather.y = 0;
        trace("Lys X-verdi: " + light_feather.x);
        sum_LightFeatherX += Number(light_feather.x);
        return sum_LightFeatherX;
    }
    trace(sum_LightFeatherX);

    dark_feather.x += sum_LightFeatherX;
    for (var j = 1; j <= bad_answers; j++) {
        addChild(dark_feather);
        dark_feather.x += 12 + (j*16);
        dark_feather.y = 0;
        trace("Mørk X-verdi: " + dark_feather.x);
    }

    /*
        //Resetter poengsummen
        good_answers = 0;
        bad_answers = 0;
    */
}

Resizing AIR for iOS and Android

I have two files; preloader.swf and game.swf. The preloader basically loads the game(.swf). I have a resize event in the preloader, which is fully functioning!

stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

stage.stageWidth = stage.fullScreenWidth;
stage.stageHeight = stage.fullScreenHeight;


trace(stage.stageWidth + "x" + stage.stageHeight);

These lines are fired at the very beginning of the script.

But the problem occurs when the game.swf is loaded. At first I tried to place the same lines at the beginning of this script, but it did not work. I tried running only the game.swf, but nothing happened. Then I tried just using the stage.stageWidth to figure out the width of the game.swf after it has been loaded in to preloader.swf, but i got an error saying:

TypeError: Error #1009: Cannot access a property or method of a null object reference.

What can I do to make sure both the preloader.swf and game.swf is the same size as the device's max? Is the game.swf's size dependent on the preloader.swf's size (if preloader.swf is 360x720, will game.swf automatically be 360x720)?

Thanks :)

replace three carriage returns with two

I have a text that has this structure line1: Sometext(followed by carriage return) line2: more text(followed by carriage return) line3: more text(followed by carriage return) line4: Carriage Return (\r)(followed by carriage return) line5: Carriage Return (\r)(followed by carriage return) line6: new text and so on

How can I replace the three carriage returns in lines (3 through 5) with something else?

I tried

var removeCR: RegExp = /[\r\n]+/g;

but that did not work. Any ideas. Thank you

AS3 - Position symbols in symbols according to stage values

I want to place a symbol (symbol2) inside another symbol (symbol1). Then I want to position that symbol (symbol2) to for example x = 50 (The stage's x = 50, not symbol1's x = 50)

symbol1.symbol2.x = 50;

This places symbol2 to the symbol1's coordinate system. Therefore; if symbol1.x = 50 and symbol1.symbol2.x = 50, symbol2 will be placed on the stages value 100.

I don't know if this was understandable. I does anyone have an idea of how to do this easily?

Passing variable from AS3 to PHP

I am currently doing a flash game that records the time taken and sending it to a php. Currently, my game is working and the time taken could be traced correctly. URLLoader is also working correctly however, my php page does not seem to be able to get the result from $_POST. I have posted my code below.

I would appreciate any help given. Have already tried various of methods but just could not work. I either get the processScore.php opening on a separate window and showing empty page or nothing happen at all. Thanks in advanced!

AS3:

function sendTime() {
        var req:URLRequest = new URLRequest("processScore.php");
        var loader:URLLoader = new URLLoader();
        //using URLLoaderDataFormat.VARIABLES give me error so I changed to TEXT.
        loader.dataFormat = URLLoaderDataFormat.TEXT;
        var toSend:URLVariables = new URLVariables();
        req.data = toSend;
        req.method = URLRequestMethod.POST;

        toSend.timeRecorded = timeTaken;

        loader.addEventListener(Event.COMPLETE, timeSent);
        loader.load(req);

    }

    function timeSent(e:Event) {
        trace("SENT");
    }

processScore.php:

<?php 
  if(isset($_POST['timeRecorded'])) {
    echo $_POST['timeRecorded'];
}
?> 

AS3 Hide external Swf

in my application I have main SWF that loads multiple SWFs and I want to hide two SWFs and show message to user. my problem is that I can't hide SWf although I tried to set their visibility to false and removeChild(swf) from the main SWF but this didn't benefit me, and SWFs are still loading in main one. note that i load SWFs using Loader class then add it to stage like this:

var myLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("myExternalSWF.swf");
myLoader.load (url);
addChild (myLoader);

Wait for the localstorage values

I'm trying to use the localstorage to get some info with Javascript and send them throw Ajax request.

The localstorage datas should be populate by a AS3 script like:

ExternalInterface.call('list', getList());

The JS get the data and try to send them

if (hasFlash === true) {
  data.hasFlash = true;
  data.list = localStorage.list;
}
AJAXPost(data);

But, the first time i load the page most of the datas are undefined. It seems that the AS3 don't have the time to populate the localstorage.

I tried to trap the localstorage event, but it did not work.

I also think to code a loop which wait for the data with an ugly setTimeOut() but it is not really elegant.

Do you think of another way to do this ?

Putting logic into JSON data

We have an engineer on our team that would like to the do the following inside of JSON data:

"visible": "$(= state 'state_c')"

Now in the model he has the following method to determine the state:

protected function getCurrentState():String
{
   var state:String = "defaultState";

   if (xxxx)
      state = "state_A";
   else if (xxxx)
      state = "state_B";
   else if (xxxx)
      state = "state_C";
   else
      state = "state_D";

   return state;
}

Now elsewhere whenever I need to update the state I would call the following:

data.state = getCurrentState();

The notation used in JSON data is in prefix notation (LISP) in case you were curious. The code where the model exists is written in AS3 and the object named 'data' above is that of type Object.

I am against this idea and I don't understand the value of putting logic into data. I have never seen a paradigm that would be used this way. I think this breaks the MVC architecture design and introduces many different problems. Here are my biggest issues with this design:

1) All the logic is type unsafe (data is type-unsafe)

2) Now the developer must know how to do three separate things to complete a task (write the programmer portion of the JSON data, write the correct prefix notation, and put correct logic in code)

3) I don't see a good way to unit test this behavior

4) Spreads logic into multiple areas of code and thus will make finding an error more difficult.

I am looking for any opinions on this matter. Why would this be a good idea? Are my reasons for disliking it valid? Is there some value I am missing?

RSAKey.sign() = wrong result

everyone!

I have some PHP code and it works fine. I need to have equivalent of this code on actionscript 3. I need your help.

$privateKeyPath = "private.key";
$message = "hello";
$privateKey = file_get_contents($privateKeyPath);
openssl_sign($message, $signature, $privateKey);

echo base64_encode($signature);

In AS3 I using as3crypto library to make sign:

private function readPrivateKey():String {
    var f:File = new File("/Users/ivan/Desktop/private.key");
    var fs:FileStream = new FileStream();
    fs.open(f,FileMode.READ);
    var key:String = fs.readUTFBytes(fs.bytesAvailable);
    fs.close();
    return key;
}

private function getSign():void {
    var message:String = "hello";
    var privateKey:String = readPrivateKey();
    var srcBA:ByteArray = new ByteArray();
    var resultBA:ByteArray = new ByteArray();
    var rsaKey:RSAKey;
    var base64encoder:Base64Encoder = new Base64Encoder();

    srcBA.writeUTFBytes(message);

    rsaKey = PEM.readRSAPrivateKey(privateKey);
    rsaKey.sign(srcBA, resultBA, srcBA.length);
    b64encoder.encodeBytes(resultBA);

    trace(b64encoder.toString());
}

I have same private key file. I expect that the output values are equals. But these values are different =( What am I doing wrong?

Thanks.

Actionscript 3 events - prevent click after move

So, I might forget some basics but I think that following code worked at some point in the past. The idea is to have 2 major events assigned to one object - mouse click and mouse move. If move fires, click should be prevented. So, this is the code.

private var _moved:Boolean;

public function Main()
{
    stage.addEventListener(MouseEvent.CLICK, stage_clickHandler);
    stage.addEventListener(MouseEvent.MOUSE_DOWN, stage_mouseDownHandler);
}

private function stage_clickHandler(event:MouseEvent):void
{
    trace(4444);
}

private function stage_mouseDownHandler(event:MouseEvent):void
{
    trace(1111111);
    stage.addEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMoveHandler);
    stage.addEventListener(MouseEvent.MOUSE_UP, stage_mouseUpHandler);
}

private function stage_mouseMoveHandler(event:MouseEvent):void
{
    _moved = true;
    trace(22222);
}

private function stage_mouseUpHandler(event:MouseEvent):void
{
    if(_moved)
    {
        event.stopImmediatePropagation();
        _moved = false;
    }

    trace(33333);
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMoveHandler);
    stage.removeEventListener(MouseEvent.MOUSE_UP, stage_mouseUpHandler);
}

And click handler is always fired. OK, suppose I missed something with stopping the event. However, I do not understand why next example does not work as I expected (assuming that Click event internally is combination of Down event followed by Up event, if I am not mistaken). The most weird part is that click handler is fired event if I remove adding click listener in the constructor (so the very first time the listener is added is at the end of Up event handler).

public function Main()
{
    stage.addEventListener(MouseEvent.CLICK, stage_clickHandler);
    stage.addEventListener(MouseEvent.MOUSE_DOWN, stage_mouseDownHandler);
}

private function stage_clickHandler(event:MouseEvent):void
{
    trace(4444);
}

private function stage_mouseDownHandler(event:MouseEvent):void
{
    trace(1111111);
    stage.addEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMoveHandler);
    stage.addEventListener(MouseEvent.MOUSE_UP, stage_mouseUpHandler);
}

private function stage_mouseMoveHandler(event:MouseEvent):void
{
    trace(22222);
    stage.removeEventListener(MouseEvent.CLICK, stage_clickHandler);
}

private function stage_mouseUpHandler(event:MouseEvent):void
{
    event.stopImmediatePropagation();
    trace(33333);
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, stage_mouseMoveHandler);
    stage.removeEventListener(MouseEvent.MOUSE_UP, stage_mouseUpHandler);

    stage.addEventListener(MouseEvent.CLICK, stage_clickHandler);
}

as3 Vertical Shooter Error 1009

I know that this question was asked many times and I've read hundreds of posts about it but I still cant find this error in my code.

Im trying to make a Vertical Shooter game, and every time i start the app i get this error.

this is my main class:

public class Main extends MovieClip
{
    public var heroShip:HeroShip; // DECLARATION FOR THE HERO SHIP
    public var enemy1:Enemy1;
    public var playerShot: PlayerShot; // CALLS THE BULLET CLASS
    private var background1:Background1; // CALLS THE BACKGROUND1 CLASS
    private var background2:Background2; //  CALLS THE BACKGROUND2 CLASS
    public static const scrollspeed:Number = 2; // SPEED OF THE SCROLLING
    public var playerShotArray:Array = new Array() // ARRAY FOR THE BULLETS
    private var fireTimer:Timer; //this creates a delay between each shot
    private var canFire:Boolean = true; //this checks if a shot can be fired                

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);              
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        //entry point

        background1 = new Background1(); //DECLARES NEW BACKGROUND1
        background2 = new Background2(); //DECLARES NEW BACKGROUND2
        //setting the backgrounds one below another
        background1.y = 0; // SETS "Y" POSITION FOR BACKGROUND1 
        // SETS "Y" POSITION FOR BACKGROUND2 TO BE AT BACKGORUND1 HEIGHT 
        background2.y = background1.height; 
        //add background at the lowest depth level
        stage.addChildAt(background1,0); // ADDS IMAGE TO STAGE
        stage.addChildAt(background2, 0); // ADDS IMAGE TO STAGE

        //sets up the timer and its listener
        // CALCULATES HOW LONG BEFORE NEXT SHOT IS POSSIBLE
        fireTimer = new Timer(1);
        fireTimer.addEventListener(TimerEvent.TIMER, 
        handlefireTimer, false,0,   true);
        stage.addEventListener(KeyboardEvent.KEY_DOWN,handleCharacterShoot);
        stage.addEventListener(Event.ENTER_FRAME, backgroundScroll);
        stage.addEventListener(Event.ENTER_FRAME, handleCharacterMovement);
        setInterval(playerShootMovement, 1);
        heroShip = new HeroShip();
        stage.addChild(heroShip);    // ADDS IMAGE TO STAGE 

        enemy1 = new Enemy1();
        enemy1.y = 50;
        enemy1.x = 50;
        stage.addChild(enemy1);

        Mouse.hide();   

        setInterval(enemysMove, 22);
    }

    private function handlefireTimer(e:TimerEvent) : void
    {
        //the timer runs, so a shot can be fired again
        canFire = true;
    }

    private function handleCharacterMovement(e:Event):void
    {   
        //values adjusted correctly so the mouse at the center of the ship 
        heroShip.x = mouseX -25;
        heroShip.y = mouseY -50;                        
    }

    public function playerShoot():void
    {
        //if canFire is true, allow a shot to 
        be fired, then set canFire to false and start the timer again
        //else, do nothing          
        if (canFire)
        {

            playerShotArray.push(playerShot = new PlayerShot);  
           //Add new line to the array

            playerShot.y = heroShip.y; //Spawn missile in ship
            playerShot.x = heroShip.x + 25;
            addChild(playerShot); // Adds bullets to the stage
            canFire = false;
            fireTimer.start(); // Timer for the bullet starts   
        }
    }

    public function playerShootMovement():void
    {

        for (var i:int = 0; i < playerShotArray.length; i++) 
        {
            playerShotArray[i].y -= 10; // HOW QUICK THE BULLETS ARE MOVING

            if (playerShotArray[i].y == 850) 
     // Once 850.y is reached the bullet is removed
            {
                playerShotArray.shift();    
  // removes bullets once they reach top of the screen
            }
        }       
    }
    public function enemysMove():void
    {
        if (enemy1.y >= 800)
        {
            enemy1.y = 0; 
        }
        else if (enemy1.x > 0)
        {
            enemy1.y +=2;
        }
            Collision();
        /*if (Car02.x >= 800)
        {
            Car02.x = 0;
        }
        else if (Car02.x >= 0)
        {
            Car02.x += 8;
        }
            Collision();*/
    }
    public function handleCharacterShoot(e:KeyboardEvent):void
    {
        /** 
         * SpaceBar = 32
         */                                 
        if (e.keyCode == 32)
        {
                playerShoot(); // once the button is pressed Bullets spawn
        }       
        trace ("Shooting");
    }       

    public function backgroundScroll (evt:Event):void
    {
        background1.y += scrollspeed;
        background2.y += scrollspeed;
        if (background1.y >= stage.stageHeight)
        {

   //the background is below the visible stage area, put 
   it above the other background       
            background1.y = background2.y - background2.height;
        }
        else if (background2.y >= stage.stageHeight)
        {
            background2.y = background1.y - background2.height;
        }           
    }
    private function Collision():void

    {
        if (playerShot.hitTestObject(enemy1))
        {
            if (enemy1.parent)
            {
                enemy1.parent.removeChild(enemy1);
                trace ("OMG I KILLD HIM");
            }
            //this.parent.removeChild(this);
            //playerShotArray.shift();
            //removeChild(playerShot);
          }
   }
   }
}

AS3 - Space Shooter Enemy Shots

I'm very new to AS3 and programming in general and I've been developing a space shooter game in AS3 and have run into trouble regarding the enemy shots. The enemies fly vertically down from the top of the screen and should fire two shots (one going left and one going right) once their y coordinates equal that of the player. This works fine, except after anything from 30 seconds to 2 minutes, the following errors occur.

TypeError: Error #1009: Cannot access a property or method of a null object reference. at EnemyShip2/fireWeapon()[G:\Games Related\1942\src\EnemyShip2.as:78] at EnemyShip2/loop2()[G:\Games Related\1942\src\EnemyShip2.as:65]

TypeError: Error #1009: Cannot access a property or method of a null object reference. at EnemyShot/removeSelf()[G:\Games Related\1942\src\EnemyShot.as:43] at EnemyShot/loop()[G:\Games Related\1942\src\EnemyShot.as:36]

Below is the relevant code, for the enemy ship class as well as the enemy shot class.

Enemy Ship

package 
{
    import flash.display.Sprite;
    import flash.display.Bitmap;
    import flash.display.Stage;
    import flash.events.Event;
    import flash.events.TimerEvent;
    import flash.utils.Timer;

    /**
     * ...
     * @author D Nelson
     */

    [Embed(source = "../assets/enemyship2.png")]
    //This enemy moves relatively slowly and fires horizontal shots
    public class EnemyShip2 extends Bitmap
    {
        private var vy:Number = 3;
        //private var ay:Number = .2;
        private var target:HeroShip;
        private var enemyShip2:EnemyShip2;
        private var enemyfireTimer:Timer;
        private var enemycanFire:Boolean = true;

        public function EnemyShip2(target:HeroShip):void
        {
            this.target = target;
            scaleX = 0.3;
            scaleY = 0.3;
            x = Math.floor(Math.random() * 550);
            y = -105;
            addEventListener(Event.ENTER_FRAME, loop2, false, 0, true);
            enemyfireTimer = new Timer(1000, 1);
            enemyfireTimer.addEventListener(TimerEvent.TIMER, handleenemyfireTimer, false, 0, true);
        }

        private function handleenemyfireTimer(e:TimerEvent) : void
        {
            //the timer runs, so a shot can be fired again
            enemycanFire = true;
        }


        private function removeSelf2():void 
        { 
            removeEventListener(Event.ENTER_FRAME, loop2);
            if (stage.contains(this))
            {
                stage.removeChild(this);
            }
        }   

        private function loop2 (e:Event):void
        {
            //vy += ay;
            y += vy;
            if (y > stage.stageHeight)
            {
                removeSelf2();
            }

            if (y >= target.y && (enemycanFire))
            {
                fireWeapon();
                enemycanFire = false;
                enemyfireTimer.start();
            }

            if (this.x > 540 || this.x < 10)
            {
                removeSelf2();
            }
        }

        private function fireWeapon():void
        {
            stage.addChild(new EnemyShot(target, x, y, -4));
            stage.addChild(new EnemyShot(target, x, y, +4));
        }
    }
}

Enemy Shot

package 
{
    import flash.display.Sprite;
    import flash.display.Bitmap;
    import flash.events.Event;
    import flash.display.Stage;

    /**
     * ...
     * @author D Nelson
     */

    [Embed(source="../assets/enemyshot.png")]
    public class EnemyShot extends Bitmap
    {
        private var speed:Number;
        private var target:HeroShip;
        private var vx:Number;

        public function EnemyShot(target:HeroShip, x:Number, y:Number, vx:Number) 
        {
            this.target = target;
            this.x = x;
            this.y = y;
            this.vx = vx;
            scaleX = 0.3;
            scaleY = 0.3; 
            addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
        }

        private function loop(e:Event) : void
        {
            x += vx;
            if (x >= 600 || x <= -50) 
            {               
                removeSelf();
            }
        }

        private function removeSelf():void 
        { 
            removeEventListener(Event.ENTER_FRAME, loop); 
            if (stage.contains(this))
            {
                stage.removeChild(this);
            }
        }    
    }
}

Also provided is the main class, in case that is of any help.

package 
{
    import flash.display.Sprite;
    import flash.display.MovieClip;
    import flash.display.DisplayObject;
    import flash.display.Stage;
    import flash.events.*;
    import flash.events.Event;  
    import flash.events.EventDispatcher;
    import flash.events.KeyboardEvent;
    import flash.events.TimerEvent;
    import flash.ui.Mouse;
    import flash.utils.*;
    import flash.utils.ByteArray;
    import flash.utils.Timer;
    import flash.text.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;

    /**
     * ...
     * @author D Nelson
     */

    public class Main extends MovieClip
    {
        [Embed(source = "snd/gamemusic2.mp3")]
        private var MySound : Class;         
        private var mainsound : Sound;
        private var shootsound: Sound = new ShootSound;
        private var sndChannel:SoundChannel = new SoundChannel;
        public var heroShip:HeroShip;
        public var enemyShip1:EnemyShip1
        public var enemyShip2:EnemyShip2
        public var enemyShip3:EnemyShip3
        public var enemyShip4:EnemyShip4
        public var bossShip: BossShip
        public var enemyShot: EnemyShot;
        public var playerShot: PlayerShot;
        private var background1:Background1;
        private var background2:Background2;
        public static const scrollspeed:Number = 2;
        public var playerShotArray:Array = new Array()
        public var enemyShotArray:Array = new Array()
        public var enemies1Array:Array = new Array()
        public var enemies2Array:Array = new Array()
        private var fireTimer:Timer; //this creates a delay between each shot
        private var canFire:Boolean = true; //this checks if a shot can be fired                

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
            mainsound = (new MySound) as Sound;
            shootsound = (new ShootSound) as Sound;
            mainsound.play();
            background1 = new Background1();
            background2 = new Background2();
            //setting the backgrounds one below another
            background1.y = 0;
            background2.y = background1.height;
            //add background at the lowest depth level
            stage.addChildAt(background1,0);
            stage.addChildAt(background2, 0);           
            //sets up the timer and its listener
            fireTimer = new Timer(250, 1);
            fireTimer.addEventListener(TimerEvent.TIMER, handlefireTimer, false, 0, true);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, handleCharacterShoot);
            //background scrolling effect
            stage.addEventListener(Event.ENTER_FRAME, backgroundScroll);
            //loop for enemy1 variety
            stage.addEventListener(Event.ENTER_FRAME, loop1, false, 0, true);
            //loop for enemy2 variety
            stage.addEventListener(Event.ENTER_FRAME, loop2, false, 0, true);
            //speed of player shots
            setInterval(playerShootMovement, 10);           
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            //entry point           
            heroShip = new HeroShip();
            stage.addChild(heroShip);

            //test values for enemies
            /*enemyShip1 = new EnemyShip1();
            stage.addChildAt(enemyShip1, 2);
            enemyShip1.y = stage.stageWidth * 0.3;
            enemyShip1.x = 300;

            enemyShip2 = new EnemyShip2();
            stage.addChildAt(enemyShip2, 2);
            enemyShip2.y = stage.stageWidth * 0.3;
            enemyShip2.x = 200;

            enemyShip3 = new EnemyShip3();
            stage.addChildAt(enemyShip3, 2);
            enemyShip3.y = stage.stageWidth * 0.3;
            enemyShip3.x = 100;

            enemyShip4 = new EnemyShip4();
            stage.addChildAt(enemyShip4, 2);
            enemyShip4.y = stage.stageWidth * 0.3;
            enemyShip4.x = 400;

            bossShip = new BossShip();
            stage.addChildAt(bossShip, 1);
            bossShip.y = 10;
            bossShip.x = 130;*/         

            Mouse.hide();           
        }

        private function handlefireTimer(e:TimerEvent) : void
        {
            //the timer runs, so a shot can be fired again
            canFire = true;
        }

        public function playerShoot():void
        {
            //if canFire is true, allow a shot to be fired, then set canFire to false and start the timer again
            //else, do nothing          
            if (canFire)
            {
                //Add new line to the array
                playerShotArray.push(playerShot = new PlayerShot);
                //Spawn missile in ship
                playerShot.y = heroShip.y;
                playerShot.x = heroShip.x+11;
                addChild(playerShot);
                canFire = false;
                fireTimer.start();              
                sndChannel = shootsound.play();
            }
        }

        public function playerShootMovement():void
        {
            //code adapted from the Pie Throw tutorial
            for (var i:int = 0; i < playerShotArray.length; i++) 
            {
                playerShotArray[i].y -= 10;

                if (playerShotArray[i].y == 850)
                {
                    playerShotArray.shift();
                }
            }           
        }

        public function handleCharacterShoot(e:KeyboardEvent):void
        {
            /** 
             * SpaceBar = 32
             */                                 
            if (e.keyCode == 32)
            {
                playerShoot();
            }           
        }       

        public function backgroundScroll (evt:Event):void
        {
            background1.y += scrollspeed;
            background2.y += scrollspeed;
            if (background1.y >= stage.stageHeight)
            {
                //the background is below the visible stage area, put it above the other background       
                background1.y = background2.y - background2.height;
            }
            else if (background2.y >= stage.stageHeight)
            {

                background2.y = background1.y - background2.height;
            }           
        }

        //EnemyShip 1 spawning
        private function loop1(e:Event):void
        {
            //generates probability for the ship to spawn (lower number to increase odds, decrease it to decrease odds)
            if (Math.floor(Math.random() * 55) == 5)
            {
                var enemyShip1:EnemyShip1 = new EnemyShip1(heroShip); 
                enemyShip1.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy1, false, 0, true);
                enemies1Array.push(enemyShip1); 
                stage.addChild(enemyShip1);
            }
        }

        private function removeEnemy1(e:Event):void
        {
            //removes the enemy that most recently left the screen from the array
            enemies1Array.splice(enemies1Array.indexOf(e.currentTarget), 1);
        }

        //EnemyShip2 spawning
        private function loop2(e:Event):void
        {
            if (Math.floor(Math.random() * 40) == 5)
            {
                var enemyShip2:EnemyShip2 = new EnemyShip2(heroShip); 
                enemyShip2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy2, false, 0, true);
                enemies2Array.push(enemyShip2); 
                stage.addChild(enemyShip2);
            }
        }

        private function removeEnemy2(e:Event):void
        {
            enemies2Array.splice(enemies2Array.indexOf(e.currentTarget), 1);
        }
    }
}

Initially I thought it was to do with enemies firing shots while being too far to either side of the screen, but that doesn't seem to be the case. Any help would be greatly appreciated.