mercredi 30 septembre 2015

Error #1009 Cannot access a property or method of a null object reference for quiz with timer and score

I've been creating a quiz with timer and score. But I've this errors which on the frame 2:26 and frame1:11. Stated there, my object was null but I've declared it as movieclip. Can someone help me?

FRAME 2:26

 start_btn.addEventListener(MouseEvent.CLICK, quizHandler1)
    function quizHandler1 (event:MouseEvent):void
    {
        if(mygroup1.selection.label == "Is")
        {
            myscore+=10; nextFrame(); 
            smiley.visible = true;
        }

        else
        {
            nextFrame(); //HERE IS THE ERROR
            smiley.visible = false;
        }
    }

FRAME 1:11

//import flash.events.MouseEvent;

stop();

start_btn.addEventListener(MouseEvent.CLICK, startQuiz)

function startQuiz(event:MouseEvent):void
{
    nextFrame();
    }

Here is my .fla file in the dropbox. http://ift.tt/1RhcVaj

When using a keyListener in Flex, how do I catch a keystroke with Alt+S?

I am using a combination of actionscript and MXML. I have my listener established but am unable to discern how to capture the keystroke of Alt+S for my web-app.

Faster method than Point.distance to calculate collision between objects?

I'm developing a game where I have lots of collisions, and it rapidly came to notice that my bottleneck is this line:

if(Point.distance(_point1, _point2) < collisionDistance){
  //do stuff
}

where _point1 and _point2 are static variables that store the positions of objects that could collide if the collisionDistance is low enough.

Do you know of any more performant method to check a simple collision between two circles?.

Local SWF file running in a browser within dropbox cannot access remote file security sandbox violation - Cross Domain Policy

I'm using dropbox to distribute large swf files with corresponding html files that load the swfs. All the large swf files access a small "Key" swf in the same folder as the html file. That all works fine. But when the large swf files also try to access a remote text file on my server I get a security sandbox violation. After reading about this, I see that this is by design for security reasons.

But there has to be a way around this without having the user authorize the domain containing the txt file. The reason I say this is because the swf files are running right from the browser on the persons computer. I then thought about a cross domain policy. Not sure what it would look like since it's a local computer that's asking. I hope this makes sense. I was hoping I could put the cross domain policy (or some other file) on the users computer right along with the other files, but I don't think that's what they're for.

This is an update to the question above as my problems relate to crossdomain policy's. I'm showing a small snippet of code that is causing this error shown in Debug mode in the Flash IDE. The code eventually gets the txt file loaded, but is delayed due to the warning I believe and I'm wondering if this can be fixed? The delay is causing an issue.

Attempting to launch and connect to Player using URL C:\Users\Jeffrey\Dropbox\Photos\ABC\bopAnimationSales\testingGettingVariablesFromExternalSWF_simplestForm3.swf [SWF] C:\Users\Jeffrey\Dropbox\Photos\ABC\bopAnimationSales\testingGettingVariablesFromExternalSWF_simplestForm3.swf - 21834 bytes after decompression Warning: Domain http://ift.tt/1JDF9pj does not specify a meta-policy. Applying default meta-policy 'master-only'. This configuration is deprecated. See http://ift.tt/TZoLx3 to fix this problem.

Complete [UnloadSWF] C:\Users\Jeffrey\Dropbox\Photos\ABC\bopAnimationSales\testingGettingVariablesFromExternalSWF_simplestForm3.swf Debug session terminated.

Here's the code:

import flash.events.*;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.system.Security;
//flash.system.Security.loadPolicyFile("http://ift.tt/1LQd3x9");

var urlRequest:URLRequest = new URLRequest("http://ift.tt/1JDF9pp" + "?" + Math.random());  // + Math.random()
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
urlLoader.load(urlRequest);

function completeHandler(e:Event):void {
    trace("Complete");
}
function ioErrorHandler(e:IOErrorEvent):void {
    trace("ioErrorHandlerJeff: " + e.toString());
    licenseKeyNotFoundScreen.visible = true;
}

Applying Drag, Snap Back Into Original Position To An Array

I am attempting to apply drag, snap back into position functions to an array with actionscript3. Here is the code so far:

var dragArray:Array = new Array;
dragArray.push(blockSmalla);
dragArray.push(blockSmallb);
dragArray.push(blockSmallc);
dragArray.push(blockSmalld);
dragArray.push(blockSmalle);

var startPosition:Point;
function drag(e:Event):void {
dragArray[i].startDrag();
startPosition = new Point( dragArray[i].x, dragArray[i].y);
}
function dragStop(e:Event):void {
dragArray[i].stopDrag();

dragArray[i].x = startPosition.x;
dragArray[i].y = startPosition.y;
startPosition = null;
}

for (var i:uint = 0; i < dragArray.length; i++) {
dragArray[i].addEventListener(MouseEvent.MOUSE_DOWN, drag);
dragArray[i].stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);
}

Not working so far. Any suggestions?

Flash VPAID AdParameters error: "Error parsing the creative data JSON -> [object Object]"

I am using this tag to a VAST xml for a test video advertisement: http://ift.tt/1N27vBi

When I put this in a VAST validator (for example this one: http://ift.tt/1WyVNzL) it works fine.

But now I am using actionscript 3 to load the swf and start it playing according to the VPAID api.

I am parsing out the AdParameters value and saving it:

var paramsXml:XML = childXml.valueOf()
var creativeData:Object = { 'AdParameters': paramsXml };
_main.creativeData = String(creativeData);

I've also tried making paramsXml a String and other types but nothing works for me. I then go to put this in the initAd() function of the VPAID ad.

_vpaidWrapper.initAd(_main.adWidth, _main.adHeight, _main._viewMode, _main._desiredBitrate, _main._creativeData, _main._environmentVars);

But every time I get this error: "Error parsing the creative data JSON -> [object Object]"

Can anyone see what I'm doing wrong and how I can correctly pass the AdParameters to the VPAID ad?

Thanks.

Dragged object tweened back into original position in actionscript 3

I have an object on my stage that can be dragged. On release, it snaps back into its orginal position. I want to be able to tween it back into its original position so that it will look smooth and not choppy. Here is the code that I have so far:

var startPosition:Point;

blockSmallz.addEventListener(MouseEvent.MOUSE_DOWN, dragz);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStopz);

function dragz(e:Event):void {
blockSmallz.startDrag();
startPosition = new Point( blockSmallz.x, blockSmallz.y);
}

function dragStopz(e:Event):void {
blockSmallz.stopDrag();
//set back or tween position

blockSmallz.x = startPosition.x;
blockSmallz.y = startPosition.y;
startPosition = null;

}

AS3 bug (does not evaluate expressions/variables inside array)

I've stumbled onto yet another fatal Flash bug, which I barely nauseous enough to describe.

Storing things in array such as below is common. level_Data_Edible is an array containing strings. You access it to find out a string based on the current level. This has worked until suddenly, without reason.

static public var comboType_14:Array =

            ["Bomb",
            Constants.level_Data_Edible[Constants.currentLevel],
            "Gem",
            Constants.level_Data_Edible[Constants.currentLevel],
            "Gem",
            Constants.level_Data_Edible[Constants.currentLevel],
            "Frog"

        ];

static public var level_Data_Edible:Array = [ null, "Fish", "Golfball", "Gloves", "Logger", "Burger", "Beer", "Snowshoes", "Smore", "Pontoon", "Binocular"];

You have to dynamically create the variable. Access it by [classname][match]. In this case ScoreKeep[match]

var match:String = "comboType_" + String(Constants.currentLevel);

Then, what's new and changed, is that now the result is always for currentLevel = 1. Even if currentLevel = 5 or 7.

Flash does not evaluate variables inside of arrays based on their current state. I don't know what it does, but this works fine in dozens of other areas of the game. For some malicious reason, not here.

Amazingly, I can't even engineer a workaround. I've tried putting a function in the array that returns the string for the currentLevel, and instead of the string it returns "Function() function" or some nonsense.

I even tried converting the array into a vector, duplicating the array, copying the string values to another array, no matter WHAT I do, Flash figures out a way to stop me. It's really, truly something else. Inhuman, malicious.

How to bring application to foreground while running in background AS3

I have created simple app that is warning me, from time to time, to do something. There is a sound that alarms me to do that particular thing and buttons to mark it as done, or to postpone action. It is running in a background normally. When time comes, I can hear a sound, but I cannot see and app in foreground to push buttons. How can I bring application in foreground programmatically instead of clickcin on icon at android desktop? I found many samples for java, but how to do it (if it is possible) in AS3?

Launch Android Emulator for debugging AIR app from Flash Buidler 4.7

Similar to how you can launch the iOS simulator from Flash Builder 4.7 and get debug (console) output, is there a way to do the same thing with the Android Emulator?

Specifically, I'd like to be able to launch my AIR app from Flash Builder in the Android Emulator and have the console output show up in Flash Builder.

Failing that, I'll research how to launch the emulator from the commandline and do it that way.

Starling scene has blank white area after browser resize

Starling scene sometimes has blank area after browser resize. Next resize though restores the scene.

Issue is appearing in browsers: Chrome/Opera. Its not possible to reproduce bug in FF.

Is it relates to browser refreshing specifics or Starling/GPU issue?

Push Notifications take too long to arrive

I'm having a weird problem with push notifications in an adobe air app for iOS and Android.

I'm using the Easy Push ANE from Milkman Games along with the One Signal service.

The problem is that notifications do arrive, but sometimes (randomly), it can take up to 15 minutes for the messages to arrive at the device after they are sent.

This is critical for my app (a taxi booking app), since i'm relying on the push notifications for the communication between the taxi app and the users app. So, for example, if a user requests a taxi, it can take up to 15 minutes for the taxi app to be notified.

Talked to One Signal support, and according to them everything is ok on their end, and if I look at the One Signal dashboard, the notifications are delivered almost instantly all the time.

What could be the reason of this delays? and what could i do to make things better?

Thank you.

Dynamic Gallery to show download and progress bar in as3

My flash project has specific task to show the dynamic gallery items based on the xml list and there is a download option is available for each gallery item.

For this i made a movieclip (imageTile) with Thumbnail,Title,Progressbar & ProgressText. See the image link

http://ift.tt/1QKW0vV

and two classes named Main.as and FileRef.as

Main.as codes

        var tileMap:Dictionary = new Dictionary();
        public var tile:ImageTile;

        addChild(wall);
        wallWidth = wall.width;
        wallHeight = wall.height;
        var columns:Number;
        var my_x:Number;
        var my_y:Number;
        var my_thumb_width:Number;
        var my_thumb_height:Number;
        var images:XMLList;
        var total:Number;
        var swipe:Number = 0;

        var myXMLLoader:URLLoader = new URLLoader();
        myXMLLoader.load(new URLRequest("gallery.xml"));
        myXMLLoader.addEventListener(Event.COMPLETE, processXML);

    function processXML(e:Event):void {
        myXML = new XML(e.target.data);

        images = myXML.IMAGE;
        total = images.length();


        myXMLLoader.removeEventListener(Event.COMPLETE, processXML);
        myXMLLoader = null;


        var loader:Loader;
        for (var i:uint = 0; i < total; i++) {
        tile = new ImageTile();
        wall.addChild(tile);

        tile.x = i % 3 * 400 + 180;
        tile.y = Math.floor(i / 3) * 650 + 250;

        var imageName:String = images[i].@FULL;
        path = images[i].@Path;
        var title:String = images[i].@Title;
        **var caption:TextField = tile.getChildByName("caption_tf") as TextField;**
        caption.text = title;
        tile.addEventListener(MouseEvent.CLICK, onTileClick(path));
        loader = new Loader();
        loader.load(new URLRequest("images/" + imageName));
        tileMap[loader] = tile;
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoad);
    }
//trace(myXML);
}


    var tileMap:Dictionary = new Dictionary();


function onImageLoad(e:Event):void {
    var loader:Loader = e.target.loader;
    var tile:ImageTile = tileMap[loader] as ImageTile;
    var image:Bitmap = loader.content as Bitmap;
    image.x = -100;
    image.y = -100;
    image.width=366;
    image.height=418;
    var textField:DisplayObject = tile.getChildByName("caption_tf");
    var textFieldDepth:int = tile.getChildIndex(textField);
    tile.addChildAt(image, textFieldDepth);
    tileMap[loader] = null;
    image.smoothing = true;
}


function onTileClick(url:String):Function {
     return function(me:MouseEvent):void {          

        path = url;
        var download:FileRef = new FileRef();
         download.downloadFile(path);
}

FileRef.as code

public var mc_loaded   : MovieClip = Main.gameInstance.tile.getChildByName("mc_loaded") as MovieClip,
           mc_progress : MovieClip = Main.gameInstance.tile.getChildByName("mc_progress") as MovieClip,
           txt_prog    : TextField = Main.gameInstance.tile.getChildByName("txt_prog") as TextField;

public function downloadFile(url:String) : void
        {
   /// Download the gallery item codes using url
}

public function progressHandler( event : ProgressEvent ) : void
        {       
            //mc_loaded.scaleX = (event.bytesLoaded / event.bytesTotal) ;
        }

        public function completeHandler( event : Event ) : void
        {
            //reset progress bar after download is finished
            mc_loaded.scaleX = 0;  // I want to use the imageTile element
            txt_prog.text = "download finished";
        }

        public function OnZipComplete(evt:flash.events.Event):void
        {
         txt_prog.text = "download finished";
        }

Download works fine, but i could not get the progress bar and progress text for every tile created.

Thanks in advance

as3 dynamic swf to flv

I need to record a dynamic SWF to FLV. Don't want to watch the whole animation. Just to get the FLV flie at the end.
If I could do it for a bunch of URLs it would be great!

I understand there is a way to do this with JSFL but my knowledge on the whole command line is very poor... :(

The SWF gets an ID and upload a picture according to the ID. Also I have different SWF (like 5 of them) according to a parameter from the URL.

Could somebody help me with this?
Does somebody know how to do this?

Thank you :]

SPP connection in AIR iOS application

I need to create a crossplatform mobile application, which supports a SPP Bluetooth connection. Is this possible on iOS or do I need to go native?

Thanks

get primary mail id of android device in AS3

hey guys need a help regarding on how can I get Primary GMail id that is being used on a particular android cell using AS3... I was able t find a code regarding on how to get the phone number but no luck yet regarding the Mail ID

flash app working when run from flash builder 4.6.0, not working when .html file is run?

My problem after building the project in flash builder 4.7 with sdk version 4.0A is as follows:-

1) when i run build-release folder from within flash builder the request from app to server works (the request is initiated in click event).

2) when i run the .html file from projects build-release folder the request is not even initiated in browser network log.

I'm using flash builder 4.7 with sdk 4.0A installed and selected. Since I'm new to actionscript and flash builder sdk, please a detailed answer will be heartly appreciated.

delete request not being sent from browser the code is like:-

public function sendDelete(params:Object):void{
        var request:URLRequest = new URLRequest(url);
        request.method = URLRequestMethod.POST;
        request.contentType = "application/json";
        request.requestHeaders = [new URLRequestHeader('X-HTTP-Method-Override', 'DELETE')];
        request.data = JSON.stringify(params);
        loader.load(request);
    }  

app when run/debug from flash builder the request get issued (seen in browsers network log), but when the app is build and run from build-release folder (i.e. running .html file) the request does not get issued (not seen in browsers network log). But if I remove the line " request.requestHeaders = [new URLRequestHeader('X-HTTP-Method-Override', 'DELETE')];" the request works even from build-release folder.

mardi 29 septembre 2015

Dragged object tweened back into original position in actionscript 3

I have an object on my stage that can be dragged. On release, it snaps back into its orginal position. I want to be able to tween it back into its original position so that it will look smooth and not choppy. Here is the code that I have so far:

var startPosition:Point;

blockSmallz.addEventListener(MouseEvent.MOUSE_DOWN, dragz);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStopz);

function dragz(e:Event):void {
blockSmallz.startDrag();
startPosition = new Point( blockSmallz.x, blockSmallz.y);
}

function dragStopz(e:Event):void {
blockSmallz.stopDrag();
//set back or tween position

blockSmallz.x = startPosition.x;
blockSmallz.y = startPosition.y;
startPosition = null;

}

How drag a Sprite smoothly on-screen in actionscript

First of all, my question is basically the same as this one:

How to drag an image to move it smoothly on screen, with ActionScript?

I want my dragged Sprites to keep up with the mouse on-screen, smoothly, without lagging behind.

And I notice that in the old ActionScript 3 Cookbook from way-back-when that they used a similar solution for their DraggableSprite as was used in the above link. Namely, use the stage instance to listen for the MouseMove event and then read from the event.stageX and stageY properties.

I've done that.

But my Sprite still doesn't stay locked with the mouse cursor. It lags behind. I feel like I must be missing something. However, if the solution posted above (ie listen for stage's MouseMove and use event.stageX/Y) is still current and the problem I'm describing should not be occurring, please also let me know. Even though it's not supposed to work, I've tried event.updateAfterEvent() and it also doesn't seem to have any positive effect.

Any help or advice would be greatly appreciated.

Here's a simple example of how I've written the handlers. It should work as-is if pasted into a new project.

I should also add that I'm compiling this as a desktop application using Adobe AIR. Would the run time be a factor???

package {
  import flash.display.Sprite;
  import flash.events.MouseEvent;

  [SWF(width="1280", height="720", frameRate="30")]
  public class test_drag extends Sprite {

    private var testDragSprite:TestDragSprite;

    public function test_drag() {
      super();

      graphics.clear();
      graphics.beginFill(0x0000FF);
      graphics.drawRect(0, 0, 1280, 720);
      graphics.endFill();

      testDragSprite = new TestDragSprite();
      addChild(testDragSprite);

      testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, testDragSprite_mouseHandler);
      testDragSprite.addEventListener(MouseEvent.MOUSE_UP, testDragSprite_mouseHandler);
    }

    private function testDragSprite_mouseHandler(e:MouseEvent):void {
      switch (e.type) {
        case MouseEvent.MOUSE_DOWN: {
          stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
          break;
        }
        case MouseEvent.MOUSE_UP: {
          stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
          break;
        }
      }
    }

    private function mouseMoveHandler(e:MouseEvent):void {
      //-20 to keep the sprite centered on the mouse
      testDragSprite.x = e.stageX - 20;
      testDragSprite.y = e.stageY - 20;
      //e.updateAfterEvent(); //strange effect, but doesn't solve the problem.
    }
  }
}
import flash.display.Sprite;
internal class TestDragSprite extends Sprite {
  public function TestDragSprite() {
    super();
    graphics.lineStyle(1, 0xDDDDDD);
    graphics.beginFill(0xFF0000);
    graphics.drawRoundRect(0, 0, 40, 40, 12);
    graphics.endFill();
  }      
}

How drag a Sprite smoothly on-screen in actionscript

First of all, my question is basically the same as this one:

How to drag an image to move it smoothly on screen, with ActionScript?

I want my dragged Sprites to keep up with the mouse on-screen, smoothly, without lagging behind.

And I notice that in the old ActionScript 3 Cookbook from way-back-when that they used a similar solution for their DraggableSprite as was used in the above link. Namely, use the stage instance to listen for the MouseMove event and then read from the event.stageX and stageY properties.

I've done that.

But my Sprite still doesn't stay locked with the mouse cursor. It lags behind. I feel like I must be missing something. However, if the solution posted above (ie listen for stage's MouseMove and use event.stageX/Y) is still current and the problem I'm describing should not be occurring, please also let me know. Even though it's not supposed to work, I've tried event.updateAfterEvent() and it also doesn't seem to have any positive effect.

Any help or advice would be greatly appreciated.

Here's a simple example of how I've written the handlers. It should work as-is if pasted into a new project.

I should also add that I'm compiling this as a desktop application using Adobe AIR. Would the run time be a factor???

package {
  import flash.display.Sprite;
  import flash.events.MouseEvent;

  [SWF(width="1280", height="720", frameRate="30")]
  public class test_drag extends Sprite {

    private var testDragSprite:TestDragSprite;

    public function test_drag() {
      super();

      graphics.clear();
      graphics.beginFill(0x0000FF);
      graphics.drawRect(0, 0, 1280, 720);
      graphics.endFill();

      testDragSprite = new TestDragSprite();
      addChild(testDragSprite);

      testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, testDragSprite_mouseHandler);
      testDragSprite.addEventListener(MouseEvent.MOUSE_UP, testDragSprite_mouseHandler);
    }

    private function testDragSprite_mouseHandler(e:MouseEvent):void {
      switch (e.type) {
        case MouseEvent.MOUSE_DOWN: {
          stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
          break;
        }
        case MouseEvent.MOUSE_UP: {
          stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
          break;
        }
      }
    }

    private function mouseMoveHandler(e:MouseEvent):void {
      //-20 to keep the sprite centered on the mouse
      testDragSprite.x = e.stageX - 20;
      testDragSprite.y = e.stageY - 20;
      //e.updateAfterEvent(); //strange effect, but doesn't solve the problem.
    }
  }
}
import flash.display.Sprite;
internal class TestDragSprite extends Sprite {
  public function TestDragSprite() {
    super();
    graphics.lineStyle(1, 0xDDDDDD);
    graphics.beginFill(0xFF0000);
    graphics.drawRoundRect(0, 0, 40, 40, 12);
    graphics.endFill();
  }      
}

Using regex to split()

I've been trying to get a regular expression to work for my code for a while and am wondering if anyone knows a better way.

I've got a big chunk of text to parse and want to split it into an array based on the lines. This would be straightforward, right? Using regex:

var re:RegExp = /\n/;    
arr = content.split(re);

Easy. But I also want to only split on lines that do not have a space after them. I figured I'd use the \S character to match anything with a non-space character after the \n.

var re:RegExp = /\n\S/;    
arr = content.split(re);

However, this now removes the first letter of every line I'm splitting (because it's matching those letters).

What's the best way to:

  1. Ignore the spaces by using a caret (I tried something like /\n^\' '/ but no luck)?
  2. Not lose that \S character when splitting the string into an array?

change text of TLFTextField through constructor

I have a symbol which extends MovieClip and it has a TLFTextField instance in it. I try to change the text of the TLFTextField in the constructor, like this:

public function mySymbol() 
{
    myTLF.text = "texty text";
}

I create a new instance of the class mySymbol in my DocumentClass:

public function DocumentClass() 
{
    var mySymbol:MySymbol = new MySymbol();
    addChild(mySymbol);
}

The symbol is created and added to stage (I know that because it has a border and background color) but nothing shows up inside myTLF.

If instead of trying to change the text in the constructor, I change it in the DocumentClass() (using mySymbol.myTLF.text = "texty text"; it does show up.

What am I missing here?

BinaryData ByteArray actionscript to PHP

In actionscript i got some DefineBinaryData and some function below:

var loc1 = new ByteArray();
loc1.endian = Endian.LITTLE_ENDIAN;
var loc2 = loc1.readInt();

var loc3 = new ByteArray();
var loc4:int = loc3.readByte();
var loc5 = loc3.readUTFBytes(loc3.length);

param1.readBytes(loc2,0,16);
loc2.position = 0;

I export these BinaryData to .bin file and read in php use fopen("bin_file", "rb") but how i can use readByte() readUTFBytes() readInt() and Endian.LITTLE_ENDIAN in PHP ?

Cant create filter on movieclips in AS3

After a long time im struggeling with flash...

I have some movieclips and i would like to get a filter only to that movieclip that i MOUSE_OVER.

There must be a diffrent way than type MOUSE_OVER and MOUSE_OUT for every single movieclip.

Flex mx Image source path at runtime

I'm wading through a Flex AIR desktop project that someone else wrote. The original author has used several mx.controls.Image components. Runtime image paths assigned like this:

image.source = "/assets/book.png";

It doesn't work - I just get the broken image icon.

I've never used the above approach in my own code. Personally, I've always used compile-time embedded images or URLLoader/Loader for runtime images.

So, I'd like to learn how to get this image path approach working.

I wrote a simple test program. Here is my .mxml -

<?xml version="1.0" encoding="utf-8"?>
 <pf:LearningAS xmlns:fx="http://ift.tt/rYUnH9"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      xmlns:pf="com.powerflasher.*">
      <mx:Image id="myImage"/>
 </pf:LearningAS>

Here is my connected .as

public class LearningAS extends WindowedApplication {

    public var myImage:Image;

    public function LearningAS() {
        super();
        addEventListener(FlexEvent.CREATION_COMPLETE, init);
    }

    protected function init(event:FlexEvent):void {
        myImage.source = '/assets/myimage.png';
    }
}

I also added the src/assets folder to AIR package contents. And I added -use-network=false to my compiler directives. (I'm using FDT, and Flex 4.6).

Delay user input for file.save() in as3?

So, the way flash works is that it requires user input in the same frame that a file.save() is called, otherwise it throws an error.

Problem

I'm using alivePDF to render out a PDF of some things on screen. It takes a few seconds to render everything, so the user is left looking at the same screen without being able to click anything, then the save dialogue pops up. I want to throw up a loading screen, just so the user is aware of what's happening. However, it wont render on screen while the PDF is being created, since the frame hasn't ended yet, so the loading screen appears just as the save dialogue is promped, so they're left looking at the same screen still.

My Temporary Solution

What I ended up doing was waiting for the PDF to load before prompting the save dialogue. However, as I said before, flash will throw an error without user input on that frame. So, I added a "save" button that prompts the dialogue. This is less than ideal, because then it's like 3 clicks to save a PDF and it's just less than desirable. Click the savePDF button, wait, click the save button again, then click the save dialogue's save button. See my issue?

Is there a way to delay the user input by 1 or 2 frames so flash will let me call the save() dialogue automatically? Or maybe force a render call mid-frame to show the loading screen while the PDF is getting ready, so that the user input, the loading screen, and the save() dialogue are called in the same frame, but the render is called at the onset of the PDF loading?

Actionscript 3.0 How do i define objects from addChild?

So basically I wanted a boy to eat up some mushrooms that was generated using addChild. and i made a hittest for it. But i had an error 1120 of undefined property. how can I slove this? any help would be much appreciated.

heres my code.

    var timer:Timer = new Timer(1000,10);
timer.addEventListener(TimerEvent.TIMER, addTarget);
timer.start();

var score:int = 0;

function addTarget(e:TimerEvent)
{
    var posX = Math.random()*860;
    var posY = Math.random()*500;


    var mushroom:Mushroom = new Mushroom();
    addChild(mushroom);


    mushroom.x = posX;
    mushroom.y = posY;
    boy_mc.addEventListener(Event.ENTER_FRAME, scoring);
}


function scoring(e:Event)
{
    trace("test");
    if (boy_mc.hitTestObject(mushroom))

    {
    score = score + (MovieClip(e.currentTarget).point);

    score_txt.text = String(score);
    }
}

----------------and heres my class file----------

package  
{
    import flash.display.MovieClip;

    public class Mushroom extends MovieClip
    {
        private var size:Number;


        public var point:int;


        public var mushroom:int;

        public function Mushroom() 
        {


            // constructor code
            size = (Math.random()*100)+20;
            this.width = size;
            this.height = size;

            point = Math.random()*10;
        }

    }

}

Next button in drag and drop button doesnt function

I am trying to create a drag and drop game. I want to create a next button and it didnt work. If I remove the next button, the drag and drop game works fine but once I add the drag and drop button, then the whole game doesnt function. Here is my code. Can anyone help me?

import flash.events.MouseEvent;




var objectOriginalX:Number;
var objectOriginalY:Number;




answer.buttonMode = true;
answer.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
answer.addEventListener(MouseEvent.MOUSE_UP, dropObject);


answer1.buttonMode = true;
answer1.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
answer1.addEventListener(MouseEvent.MOUSE_UP, dropObject);




answer2.buttonMode = true;
answer2.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
answer2.addEventListener(MouseEvent.MOUSE_UP, dropObject);


answer3.buttonMode = true;
answer3.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
answer3.addEventListener(MouseEvent.MOUSE_UP, dropObject);

next_btn.buttonMode = true;
next_btn.addEventListener(MouseEvent.CLICK, next_btn);


/*next_btn.addEventListener(MouseEvent.CLICK,next_btn)
next_btn.buttonMode = true;*/

/*stop();
function next_btn(event:MouseEvent):void 
{
      gotoAndStop(5);
}*/


function pickObject(event:MouseEvent):void
{
  event.target.startDrag();
  event.target.parent.addChild(event.target);
  objectOriginalX = event.target.x;
  objectOriginalY = event.target.y;
}


function dropObject (event:MouseEvent):void
{
  event.target.stopDrag();
  var matchingTargetName:String = event.target.name + "Target" ;
  var matchingTarget: DisplayObject = getChildByName(matchingTargetName);

  if(event.target.dropTarget != null && event.target.dropTarget.parent == matchingTarget)
  {
  event.target.removeEventListener(MouseEvent.MOUSE_DOWN,pickObject);
  event.target.removeEventListener(MouseEvent.MOUSE_UP,dropObject);
  event.target.buttonMode = false;
  event.target.x = matchingTarget.x;
  event.target.y = matchingTarget.y;

  }

  else   { 
  event.target.x = objectOriginalX;
  event.target.y = objectOriginalY;
  }

  function next_btn.MovieClip(event:MouseEvent):void 
{
      gotoAndStop(5);
}

}


stop();

find out what is inside a function

For example, there is a function like this:

function a(){
    if(stage.color==0xffffff){
        trace("The color of stage is White");
    }
}

now, can I get a String, XML or anything else that shows me what this function does?
something that shows me this:

    if(stage.color==0xffffff){
        trace("The color of stage is White");
    }

Thanks.

Accurate scale formula for endless road

I'm making an endless straight road from top to bottom and using a single bitmapData for it that I use in multiple tiles. Those tiles are arranged correctly from top to bottom (let's say top to bottom of screen) by using a formula that calculates what their scale values should be. The scale value of the first tile is calculated according to its position then all other tile are calculated according to their previous tile. This works great except that when everything loops I can see the bottom tile (the first one) having its width getting slightly larger than it should (around 5 pixels too large). When that first tile goes out of screen it's sent back to the top of screen and the next tile takes the role of top tile, etc ... But because of the slight width enlargement the road has a slight jump in size when the transition occurs. So that means my formula is close but slightly wrong in calculating the scale of the first tile. What is wrong with the formula and what should be corrected?

var speedFactor:Number = speed / _length;//size of screen top to bottom 
var bitmap:RoadTile = tiles[0]; 
bitmap.y += speedFactor * bitmap.y; //scaled speed      
var distance:Number = _length - bitmap.y;//calculate position and determine scale           
if(distance < 0)
{
    distance = _length + Math.abs(distance);
}
else
{
    distance = bitmap.y;
}           
var scale:Number = (distance / _length);    
bitmap.scaleX = bitmap.scaleY = scale;  
//scale is calculated but is slightly wrong.

You can see the result here: http://ift.tt/1iYKP8v

Notice the bottom of the screen where the width of the road slightly changes and then jumps back to normal when the top tile is removed and sent back to the beginning. I now got a better result by applying a mask but that's really just a hack. I also got a better result by adjusting the scale of the top tile according to the width it needs to be at the bottom of the screen. Still not perfect though.

I think I know what I'm missing and I'm gonna work on that: adding in the formula the angle of the graphic. Here the tile side have a angle of 28 (the engine works with tile of different side angle). Basically the angle needs to be added to the formula so that when the top tile moves down, its new scale is calculated according to what the tile width needs to be at the bottom of the screen (that width needs to always be the same so no jump occur in the road display)

How to add, edit, delete and save xml node in as3

My xml file is like this,

<GALLERY COLUMNS="3" XPOSITION="30" YPOSITION="30" WIDTH="150" HEIGHT="150">
<IMAGE FULL="Tinku.png" Title="Tinku" THUMB="thumbs/thumb1.jpg" Path="file:///storage/emulated/0/Raconteur/Tinku" />
<IMAGE FULL="Kaal.png" Title="Kaal" THUMB="thumbs/thumb2.jpg" Path="file:///storage/emulated/0/Raconteur/Kaal" />
<IMAGE FULL="Painters.png" Title="Little Painters" THUMB="thumbs/thumb3.jpg" Path="file:///storage/emulated/0/Raconteur/Painters" />
</GALLERY>

How to add a new node like the one below,

<IMAGE FULL="Lost.png" Title="Lost and Found" THUMB="thumbs/thumb4.jpg" Path="file:///storage/emulated/0/Raconteur/Lost" />

Also i want to know how to delete a particular node

var myXMLLoader:URLLoader = new URLLoader();
            myXMLLoader.load(new URLRequest("gallery.xml"));
            myXMLLoader.addEventListener(Event.COMPLETE, processXML);

        function processXML(e:Event):void {
            myXML = new XML(e.target.data);
            images = myXML.IMAGE;
            total = images.length();
            myXMLLoader.removeEventListener(Event.COMPLETE, processXML);
            myXMLLoader = null;             
            var imageName:String = images[i].@FULL;
            loader = new Loader();
            loader.load(new URLRequest("images/" + imageName));
        }

add_bt.addEventListener(MouseEvent.CLICK, addnode);
private function addnode(e:MouseEvent):void
        {
            var new_node:XML = <IMAGE FULL="Lost.png" Title="Lost and Found" THUMB="thumbs/thumb4.jpg" Path="file:///storage/emulated/0/Raconteur/Lost" />
            myXML.appendChild(new_node);
            trace(myXML);
        }

Thanks in advance

flash app working when run from flash builder 4.7, not working when .html file is run?

My problem after building the project in flash builder 4.7 with sdk version 4.0A is as follows:-

1) when i run build-release folder from within flash builder the request from app to server works (the request is initiated in click event).

2) when i run the .html file from projects build-release folder the request is not even initiated in browser network log.

I'm using flash builder 4.7 with sdk 4.0A installed and selected. Since I'm new to actionscript and flash builder sdk, please a detailed answer will be heartly appreciated.

AS3 : cannot fill subject and body in mailto

I am currently programming using as3 and I want to fill subject and body of my mail using mailto.

I tried everything I've seen on Internet but nothing worked :(

This is my entire code:

import flash.display.Sprite; 
import flash.net.URLRequest;
import flash.net.navigateToURL;

function openMailClient(event:MouseEvent):void
{
   var mail:URLRequest = new URLRequest("mailto:hi@hi.com?subject=hi&body=hi");
   navigateToURL(mail);
}
stage.addEventListener(MouseEvent.CLICK, openMailClient);

Can someone help me?

Flex mx Image source path at runtime

I'm wading through a Flex AIR desktop project that someone else wrote. The original author has used several mx.controls.Image components. Runtime image paths assigned like this:

image.source = "/assets/book.png";

It doesn't work - I just get the broken image icon.

I've never used the above approach in my own code. Personally, I've always used compile-time embedded images or URLLoader/Loader for runtime images.

So, I'd like to learn how to get this image path approach working.

I wrote a simple test program. Here is my .mxml -

<?xml version="1.0" encoding="utf-8"?>
 <pf:LearningAS xmlns:fx="http://ift.tt/rYUnH9"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      xmlns:pf="com.powerflasher.*">
      <mx:Image id="myImage"/>
 </pf:LearningAS>

Here is my connected .as

public class LearningAS extends WindowedApplication {

    public var myImage:Image;

    public function LearningAS() {
        super();
        addEventListener(FlexEvent.CREATION_COMPLETE, init);
    }

    protected function init(event:FlexEvent):void {
        myImage.source = '/assets/myimage.png';
    }
}

I also added the src/assets folder to AIR package contents. And I added -use-network=false to my compiler directives. (I'm using FDT, and Flex 4.6).

Unable to add include ANE File in ANT Script

I wanted to create an ANT Script to create build in one click for my Flex Mobile Project. My app using some native extension file(.ane). When I tried to run the ANT script it saying -

An implementation for native extension 'com.example.mobile.extensions.NativeFeature' required by the application was not found for the target platform 

I am using below code to include ane file in ANT Script.

<compiler.external-library-path dir="${basedir}/ane" append="true">   
                <include name="**/*.ane"/>   
            </compiler.external-library-path> 

Also added the same extensionId in myApp-app.xml file which I used in my extension.xml file.

lundi 28 septembre 2015

Convert from one range to another

I have two sets of ranges that I need to be translated from one to the other.

The first range is -100 ↔ 100 with 0 being default.

The second range is 0.0 ↔ 10.0 with 1 being default.

I am working in AS3 with the first range and the second range is a python class and I need these numbers to line up.

I am adjusting brightness of a video in realtime with a slider. The video filter accepts values between -100 ↔ 100. I need to then take that value and pass it to a python script but it only accepts values from 0.0 ↔ 10.0

I tried this function I found on the net, but it doesn't translate the values correctly in this particular case.

private function convertRange(originalStart:Number,originalEnd:Number,newStart:Number,newEnd:Number,value:Number):Number
{
    var originalRange:Number = originalEnd - originalStart;
    var newRange:Number = newEnd - newStart;
    var ratio:Number = newRange / originalRange;
    var newValue:Number = value * ratio;
    var finalValue:Number = newValue + newStart;
    return finalValue;
}       

Is this even possible? Hopefully my question is clear, please let me know if it needs clarification.

This is the python class I am referring to: http://ift.tt/1KGjWyZ It uses the second range whereas AS3 uses the first range.

Show the submenu on mouse over instead of mouse click in MenuBar in Flex 4.6

I am working in Flex 4.6 web application. I have a menubar when i click on that submenu is being open after that it works on mouse over. Now the problem is I want it on mouse over when i over the mouse on menubar submenu should open not onclick. How can i do it. Please give me your advice.

Thanks Bikrant Singh

Scoring system not working AS3

it's me again, I've finnaly made the math generator to work and see if the answer is correct or incorrect ("horray!") but, this is programming, and another error apeared ("darnit..."). so I added a scoring system and at the first correct answer it gives me 1 point but at the second correct answer it doesn't give me another point, it stays at 1 point :(. Also, is there a way to block the "verificar" button until the "startButton" button is pressed? (so people that try my math generator don't cheat!) Thank you very much for your help!

import flash.utils.Timer;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
stop()
var reloj:Timer = new Timer(1000,60);
startButton.addEventListener(MouseEvent.CLICK, startTimer);
reloj.addEventListener(TimerEvent.TIMER, moveHand);
reloj.addEventListener(TimerEvent.TIMER_COMPLETE, endTimer);
function startTimer(e:MouseEvent):void
{
        reloj.start();
        startButton.visible = false;
}
function moveHand(e:TimerEvent):void
{
        segundero.rotation = segundero.rotation + 6
}
function endTimer(e:TimerEvent):void
{
        trace("Se agotó el tiempo");
        gotoAndPlay (1, "1");
}
nuevo.addEventListener(MouseEvent.CLICK, generarPregunta);
function generarPregunta(MouseEvent):void
{
        var random1:Number = Math.floor(Math.random()*25)
        var random2:Number = Math.floor(Math.random()*25)
        var array:Array = new Array ("+","-","*","/")
        var randomIndex:int = Math.floor (Math.random()*4)
        SimbMat.text = array [ randomIndex ]
        numI.text = random1 + ""
        numD.text = random2 + ""
}

verificar.addEventListener(MouseEvent.CLICK, verificarRespuesta);
function verificarRespuesta(MouseEvent):void
{
    var puntaje:int = 0
        if (String(SimbMat.text) == "+")
        {
                if (Number(numI.text) + Number(numD.text) == Number(imput.text))
                    {
                                trace("correcto")
                                puntaje++;
                                updateScore();
                                generarPregunta(MouseEvent);
                        }
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat.text) == "-")
        {
                if (Number(numI.text) - Number(numD.text) == Number(imput.text))
                {
                        trace("correcto")
                        puntaje++;
                        updateScore();
                        generarPregunta(MouseEvent);
                }
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat.text) == "*")
        {
                if (Number(numI.text) * Number(numD.text) == Number(imput.text))
                {
                        trace("correcto")
                        puntaje++;
                        updateScore();
                        generarPregunta(MouseEvent);
                }
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat.text) == "/")
        {
                if (Number(numI.text) / Number(numD.text) == Number(imput.text))
                {
                        trace("correcto")
                        puntaje++;
                        updateScore();
                        generarPregunta(MouseEvent);
                }
                else
                {trace("incorrecto")}
        }
                
        function updateScore() :void
{
        score.text = "Puntaje: " + puntaje;
}
}

Action script 3.0 Typing Test

I am needing to create a typing test that I can integrate in with an Abode Captivate training simulation I have created. I am having to create a widget in flash professional. I have been able to create one in HTML and was just going to try and replicate it in Flash Professional. Is that even possible or would I have to completely re-write my code in flash professional?

Here is my HTML code and I am wanting it in Flash Professional using ActionScript 3.0.

<!DOCTYPE html>
<html>

<HEAD>

  <script language="JavaScript">
    msg = new Array("After awhile, finding that nothing more happened, she decided on going into the garden at once; but, alas for poor Alice! When she got to the door, she found she had forgotten the little golden key, and when she went back to the table for it, she found she could not possibly reach it: she could see it quite plainly through the glass and she tried her best to climb up one of the legs of the table, but it was too slippery, and when she had tired herself out with trying, the poor little thing sat down and cried.")
     word = 10

    function m() {
      msg = new Array("After awhile, finding that nothing more happened, she decided on going into the garden at once; but, alas for poor Alice! When she got to the door, she found she had forgotten the little golden key, and when she went back to the table for it, she found she could not possibly reach it: she could see it quite plainly through the glass and she tried her best to climb up one of the legs of the table, but it was too slippery, and when she had tired herself out with trying, the poor little thing sat down and cried.")
      word = 10
    }


    function beginIt() {
      randNum = Math.floor((Math.random() * 10)) % 4
      msgType = msg
      day = new Date();
      startType = day.getTime();
      document.theForm.given.value = msgType
      document.theForm.typed.focus();
      document.theForm.typed.select();
    }

    function cheat() {
      alert("You can not change that!");
      document.theForm.typed.focus();
    }

    function stopIt() {
      dayTwo = new Date();
      endType = dayTwo.getTime();
      totalTime = ((endType - startType) / 1000)
      spd = Math.round((word / totalTime) * 60)

      if (document.theForm.typed.value == document.theForm.given.value) {
        alert("\nYou typed a " + word + " word sentence in " + totalTime + " seconds, a speed of about " + spd + " words per minute!")
      } else {
        alert("You made an error, but typed at a speed of " + spd + " words per minute.")
      }
    }
  </script>

</head>

<body>
  <center>
    <form name="theForm">
      <table border=3 cellspacing=0 cellpadding=0>
        <tr>
          <td colspan=2>
            <br>
            <center>
              <input type=button value="Start Typing Test" name="start" onClick="beginIt()">
            </center>
            <P>
              <textarea name="given" cols=53 rows=10 wrap=on onFocus="cheat()"></textarea>
          </TD>
        </tr>
        <tr>
          <td colspan=2>
            <center>
              <input type=text name="typed" size=45>
              <input type=button value="DONE" name="stop" onClick="stopIt()">
            </center>
          </TD>
        </tr>
      </table>
    </form>
  </center>
</body>

</html>

Convert from one range to another

I have two sets of ranges that I need to be translated from one to the other.

The first range is -100 ↔ 100 with 0 being default.

The second range is 0.0 ↔ 10.0 with 1 being default.

I am working in AS3 with the first range and the second range is a python class and I need these numbers to line up.

I am adjusting brightness of a video in realtime with a slider. The video filter accepts values between -100 ↔ 100. I need to then take that value and pass it to a python script but it only accepts values from 0.0 ↔ 10.0

I tried this function I found on the net, but it doesn't translate the values correctly in this particular case.

private function convertRange(originalStart:Number,originalEnd:Number,newStart:Number,newEnd:Number,value:Number):Number
{
    var originalRange:Number = originalEnd - originalStart;
    var newRange:Number = newEnd - newStart;
    var ratio:Number = newRange / originalRange;
    var newValue:Number = value * ratio;
    var finalValue:Number = newValue + newStart;
    return finalValue;
}       

Is this even possible? Hopefully my question is clear, please let me know if it needs clarification.

This is the python class I am referring to: http://ift.tt/1KGjWyZ It uses the second range whereas AS3 uses the first range.

Accurate scale formula for endless road

I'm making an endless straight road from top to bottom and using a single bitmapData for it that I use in multiple tiles. Those tiles are arranged correctly from top to bottom (let's say top to bottom of screen) by using a formula that calculates what their scale values should be. The scale value of the first tile is calculated according to its position then all other tile are calculated according to their previous tile. This works great except that when everything loops I can see the bottom tile (the first one) having its width getting slightly larger than it should (around 5 pixels too large). When that first tile goes out of screen it's sent back to the top of screen and the next tile takes the role of top tile, etc ... But because of the slight width enlargement the road has a slight jump in size when the transition occurs. So that means my formula is close but slightly wrong in calculating the scale of the first tile. What is wrong with the formula and what should be corrected?

var speedFactor:Number = speed / _length;//size of screen top to bottom 
var bitmap:RoadTile = tiles[0]; 
bitmap.y += speedFactor * bitmap.y; //scaled speed      
var distance:Number = _length - bitmap.y;//calculate position and determine scale           
if(distance < 0)
{
    distance = _length + Math.abs(distance);
}
else
{
    distance = bitmap.y;
}           
var scale:Number = (distance / _length);    
bitmap.scaleX = bitmap.scaleY = scale;  
//scale is calculated but is slightly wrong.

TweenLite/TweenMax support for ConvolutionFilter

I am applying filters to a bitmap using something like:

TweenLite.to(origBitmap,0,{colorMatrixFilter:{saturation:2,brightness:3});

and that works fine.

I need to somehow apply a sharpen filter to origBitmap which I have successfully achieved using a ConvolutionFilter. The problem is after I've ran the above tweenlite call, then create a convolution filter and apply it to origBitmap, it removes the initial saturation and brightness filters and just keeps the sharpen filter

private function applyEffects(effects:Array):void
{
  currentEffects = effects;
  var props:Object = {};
  for (var i:String in effects)
  {
    props[effects[i].effect] = effects[i].amount;
  }
  TweenLite.to(bitmap,0,{colorMatrixFilter:props});
  //-- props could look like {saturation:2,brightness:3}


  //-- This will sharpen the container sprite
  var matrix:Array = [0, -1,  0,
                     -1,  5, -1,
                      0, -1,  0];
  var conv:ConvolutionFilter = new ConvolutionFilter();
  conv.matrixX = 3;
  conv.matrixY = 3;
  conv.matrix = matrix;
  conv.divisor = 1; 
  bitmap.filters = [conv]; //-- this removes the above filters and just sharpens the image
}

Is there a way to also incorporate the ConvolutionFilter in that TweenLite call above? I've searched quite a bit and found some guy made a class called TweenMan which was based around your class where ConvolutionFilter is incorporated: http://ift.tt/1GcBqi8

The movement of one pixel as3 [on hold]

As from the vector

enter link description here

to make such a move?

enter link description here

For each frame turned integer

how to translate from actionscript to java

I have this actionscript code

aaa = Hex.toArray(Hex.fromString(funcname))


public static function get funcname() : String
{
return "1111";
}

how I can this code implement to java ?

how fix overloaded constructor in actionscript

I have error in SWF project. I have this class

package managers.styles
{
   import com.codeazur.as3swf.*;
   import com.codeazur.as3swf.tags.*;

   public class CSSStyleManager extends Object
   {

      private static var _swf:SWF;

      public function CSSStyleManager()
      {
         super();
      }

      public static function setStyle(cls:Class) : void
      {
         _swf = new SWF(new cls());
      }

      public static function getCustomStyleName() : String
      {
         var len:uint = _swf.tags.length;
         for(var i:uint = 0; i < len; )
         {
            if(_swf.tags[i].type == TagCustom.TYPE)
            {
               return TagCustom(_swf.tags[i]).readString();
            }
            i++;
         }
         return "";
      }
   }
}

in function getCustomStyleName have function TagCustom(_swf.tags[i]), but in project have only this TagCustom class without parameter in constructor

package com.codeazur.as3swf.tags
{
   import com.codeazur.as3swf.*;

   public class TagCustom extends Object implements ITag
   {

      public static const TYPE:uint = 100;

      public var customData:SWFData;

      public function TagCustom()
      {
         this.customData = new SWFData();
         super();
      }

      public function parse(data:SWFData, length:uint, version:uint, async:Boolean = false) : void
      {
         data.readBytes(this.customData);
      }

      public function publish(data:SWFData, version:uint) : void
      {
         var body:SWFData = new SWFData();
         body.writeBytes(this.customData);
         data.writeTagHeader(this.type,body.length);
         data.writeBytes(body);
      }

      public function writeString(str:String) : void
      {
         this.customData.writeString(str);
      }

      public function readString() : String
      {
         return this.customData.readString();
      }

      public function get type() : uint
      {
         return TYPE;
      }

      public function get name() : String
      {
         return "CustomTag";
      }

      public function get version() : uint
      {
         return 1;
      }

      public function get level() : uint
      {
         return 1;
      }

      public function toString(indent:uint = 0) : String
      {
         var str:String = Tag.toStringCommon(this.type,this.name,indent);
         str = str + (" customData length=" + this.customData.length);
         return str;
      }
   }
}

how I can understand what is a happen

Flex - Page content changes its position automatically

I might have wrongly titled my question, but basically, on execution my flex application displays this AIS Queue list as follows:

enter image description here

One can see the huge gap between the links at the top(Home, News etc) and the AIS Queue list heading. On the left of AIS Queue table, I have rounded off the MENU option. On bringing my mouse over it, the UI changes as below(It expands the Menu):

enter image description here

Now, the AIS Queue list content has shifted to its normal position(where it should be in the page). I want this content to be in it's normal position even when the left menu is not expanded. Is this a flex issue or some resolution problem?

dimanche 27 septembre 2015

Flex mx Image source path at runtime

I'm wading through a Flex AIR desktop project that someone else wrote. The original author has used several mx.controls.Image components. Runtime image paths assigned like this:

image.source = "/assets/book.png";

It doesn't work - I just get the broken image icon.

I've never used the above approach in my own code. Personally, I've always used compile-time embedded images or URLLoader/Loader for runtime images.

So, I'd like to learn how to get this image path approach working.

I wrote a simple test program. Here is my .mxml -

<?xml version="1.0" encoding="utf-8"?>
 <pf:LearningAS xmlns:fx="http://ift.tt/rYUnH9"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      xmlns:pf="com.powerflasher.*">
      <mx:Image id="myImage"/>
 </pf:LearningAS>

Here is my connected .as

public class LearningAS extends WindowedApplication {

    public var myImage:Image;

    public function LearningAS() {
        super();
        addEventListener(FlexEvent.CREATION_COMPLETE, init);
    }

    protected function init(event:FlexEvent):void {
        myImage.source = '/assets/myimage.png';
    }
}

I also added the src/assets folder to AIR package contents. And I added -use-network=false to my compiler directives. (I'm using FDT, and Flex 4.6).

How to add, edit, delete and save xml node in as3

My xml file is like this,

<GALLERY COLUMNS="3" XPOSITION="30" YPOSITION="30" WIDTH="150" HEIGHT="150">
<IMAGE FULL="Tinku.png" Title="Tinku" THUMB="thumbs/thumb1.jpg" Path="file:///storage/emulated/0/Raconteur/Tinku" />
<IMAGE FULL="Kaal.png" Title="Kaal" THUMB="thumbs/thumb2.jpg" Path="file:///storage/emulated/0/Raconteur/Kaal" />
<IMAGE FULL="Painters.png" Title="Little Painters" THUMB="thumbs/thumb3.jpg" Path="file:///storage/emulated/0/Raconteur/Painters" />
</GALLERY>

How to add a new node like the one below,

<IMAGE FULL="Lost.png" Title="Lost and Found" THUMB="thumbs/thumb4.jpg" Path="file:///storage/emulated/0/Raconteur/Lost" />

Also i want to know how to delete a particular node

Thanks in advance

Passing a Flex VO to Coldfusion with a remoteObject function

I'm redesigning a user registration form to decouple my UI from my SQL back-end by using value objects(VO). I know how to pass form fields into a CFC through use of a remote object using <mx:RemoteObject> <mx:Method></mx:RemoteObject> where <mx:Method> references the function in the CFC that flex form elements are being passed to.

What I want to do is pass my entire VO into my CFC service to be inserted in the DB table. Most of the code I've seen attempting to do that doesn't seem to work. Can someone recommend how to best pass a VO from flex to Coldfusion?

Thank you!

Verification button not working AS3

I'm new to programming and I've made a math question generator in as3 But it doesn't seem to be working the timer isn't the problem, the problem is (see line 34 and below) that it doesn't trace "correcto" when I click on the "verificar" button when the imput text has the right answer. please help, and please, again, consider that i'm new to programming. Any help is accepted, thank you. :)

import flash.utils.Timer;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
stop()
var reloj:Timer = new Timer(1000,60);
startButton.addEventListener(MouseEvent.CLICK, startTimer);
reloj.addEventListener(TimerEvent.TIMER, moveHand);
reloj.addEventListener(TimerEvent.TIMER_COMPLETE, endTimer);
function startTimer(e:MouseEvent):void
{
        reloj.start();
        startButton.visible = false;
}
function moveHand(e:TimerEvent):void
{
        segundero.rotation = segundero.rotation + 6
}
function endTimer(e:TimerEvent):void
{
        trace("Se agotó el tiempo");
        gotoAndPlay (1, "1");
}
nuevo.addEventListener(MouseEvent.CLICK, generarPregunta);
function generarPregunta(MouseEvent):void
{
        var random1:Number = Math.floor(Math.random()*25)
        var random2:Number = Math.floor(Math.random()*25)
        var array:Array = new Array ("+","-","*","/")
        var randomIndex:int = Math.floor (Math.random()*4)
        SimbMat.text = array [ randomIndex ]
        numI.text = random1 + ""
        numD.text = random2 + ""
}
verificar.addEventListener(MouseEvent.CLICK, verificarRespuesta);
function verificarRespuesta(MouseEvent):void
{
        if (String(SimbMat) == "+")
        {
                if (Number(numI.text) + Number(numD.text) == Number(imput.text))
                {trace("correcto")}
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat) == "-")
        {
                if (Number(numI.text) - Number(numD.text) == Number(imput.text))
                {trace("correcto")}
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat) == "*")
        {
                if (Number(numI.text) * Number(numD.text) == Number(imput.text))
                {trace("correcto")}
                else
                {trace("incorrecto")}
        }
        else if (String(SimbMat) == "/")
        {
                if (Number(numI.text) / Number(numD.text) == Number(imput.text))
                {trace("correcto")}
                else
                {trace("incorrecto")}
        }
}

AS3 Bitmap Collision detection for rotated movie clips

I've constructed a Bitmap Collision system for rotated movieclips (using rotateAroundExternalPoint, not included here), yet it's sometimes off after rotation and detects collision many pixels away at certain angles even when matrices were used. I think it might be connected with bounding boxes ( getBounds(this) ), but I'm not sure how to offset that if that's the problem.

Here is a picture of two simple shapes showing collision while still not touching (ignore the black space): Simple Shapes show collision

function bitmapCollision(one:MovieClip,two:MovieClip){

if(one.hitTestObject(two)){     //hitboxes overlap = close enough to test
    var point1:Point;
    var point2:Point;
    var bmp1:BitmapData;
    var bmp2:BitmapData;
    var box1:Rectangle;
    var box2:Rectangle;
    var angle1:Number;
    var angle2:Number;
    var one_newX:Number;
    var one_newY:Number;
    var two_newX:Number;
    var two_newY:Number;
    var m1:Matrix = new Matrix();
    var m2:Matrix = new Matrix(); 
    box1 = one.getBounds(this);
    box2 = two.getBounds(this);
    one_newX = one.x - box1.x;
    one_newY = one.y - box1.y;

    m1 = one.transform.matrix;
    m2 = two.transform.matrix;
    m1.tx = 0;
    m1.ty = 0;
    m2.tx = 0;
    m2.ty = 0;

    m1.translate(one_newX, one_newY);
    m2.translate(two_newX, two_newY);

    bmp1 = new BitmapData(box1.width, box1.height, true, 0x00000000);
    bmp2 = new BitmapData(box2.width, box2.height, true, 0x00000000);

    bmp1.draw(one, m1);
    bmp2.draw(two, m2);

    point1 = new Point(box1.x, box1.y);
    point2 = new Point(box2.x, box2.y);

    if( bmp1.hitTest(point1, 50, bmp2, point2, 50) ){
        trace("Collision of "+one.name+" and "+two.name)
        collisionDetected = true;

        //Tint change for both objects
        colorTint = one.transform.colorTransform;
        colorTint.redOffset = 227;
        colorTint.blueOffset = 0;
        colorTint.greenOffset = 153;
        one.transform.colorTransform = colorTint;
        colorTint = two.transform.colorTransform;
        colorTint.redOffset = 227;
        colorTint.blueOffset = 0;
        colorTint.greenOffset = 153;
        two.transform.colorTransform = colorTint;
    }
}
}

Any ideas would be greatly appreciated :)

samedi 26 septembre 2015

Actionscript button bar not showing Hebrew letters

I've declared a bindable array like this:

[Bindable]
var lettersDS:Array = new Array('#','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','א','ב','ג','ד','ה','ו','ז','ח','ט','י','כ','ל','מ','נ','ס','ע','פ','צ','ק','ר','ש','ת');

As you can see, the array inludes the English Alphabet as well as the Hebrew one.

in the MXML I've declared a ButtonBar that uses the above array as a datasource:

<s:ButtonBar id="btnBar" color="black" click="btnBar_clickHandler(event)" height="100%" buttonMode="true" chromeColor="{Constants.FontColor}" textAlign="center" width="100%" skinClass="spark.skins.mobile.ButtonBarSkin">
                            <s:layout>
                                <s:VerticalLayout gap="-1" horizontalAlign="center" verticalAlign="middle" />
                            </s:layout>
                            <s:dataProvider>
                                <s:ArrayList source="{lettersDS}" />
                            </s:dataProvider>
</s:ButtonBar>

However, when it runs only the English letters are displayed in the buttons, the Hebrew ones are not (their buttons have no labels, they are empty).

What am I doing wrong?

Thanks,

Emeleme

Local SWF file running in a browser within dropbox cannot access remote file security sandbox violation - Cross Domain Policy

I'm using dropbox to distribute large swf files with corresponding html files that load the swfs. All the large swf files access a small "Key" swf in the same folder as the html file. That all works fine. But when the large swf files also try to access a remote text file on my server I get a security sandbox violation. After reading about this, I see that this is by design for security reasons.

But there has to be a way around this without having the user authorize the domain containing the txt file. The reason I say this is because the swf files are running right from the browser on the persons computer. I then thought about a cross domain policy. Not sure what it would look like since it's a local computer that's asking. I hope this makes sense. I was hoping I could put the cross domain policy (or some other file) on the users computer right along with the other files, but I don't think that's what they're for.

Play only a certain range of frames

I have a combobox on the stage and changing its value I want to play only a certain range of frames:

stop();

combo01.addEventListener(Event.CHANGE, change);

function change(event:Event):void{
    if (combo01.selectedItem.label == "BAL"){
        gotoAndPlay(50);
        if (currentFrame == 99) {stop();}

    }
}

The game is not stopped but returned to frame 1.

Error in physics as3

Help me find the error in physics as3. After the addition of gravity errors. hero enters the platform How to create the correct physics, physics?

mc - Sprite (Circle) kv - Sprite (Platform irregular shape)

import flash.events.Event;

var gradus: Number ;
var speed: Number = 1;
var direction: Point;
const gravity: Point = new Point(0, 0.001);
var i: int;

direction = getStartDirection(speed, 90);
stage.addEventListener(Event.ENTER_FRAME, ef);

function addVector(v1: Point, v2: Point): Point
{
    return new Point(v1.x + v2.x, v1.y + v2.y);
}

function getStartDirection(length: Number, angle: Number): Point
{
    var aRad: Number = (angle * Math.PI) / 180;
    var xpos: Number = length * Math.cos(aRad);
    var ypos: Number = length * Math.sin(aRad);
    return new Point(xpos, ypos);
}
function ef(e: Event): void
{
    for (i = 0; i < 10; i++)
    {
        mc.x += direction.x;
        mc.y += direction.y;
        var test: Number = hitTestAngle(kv, mc.x, mc.y, 10);
        if (test)
        {
            var a1: Number = (Math.atan2(direction.y, direction.x)) * (180 / Math.PI);
            gradus = test - (360 - 90 - test - (90 - a1));

            if (speed > 0.01)
            {
                speed /= 1.05;
            }
            else
            {
                speed = 0;
            }
            direction = getStartDirection(speed, gradus);
        }
        else
        {
            direction = addVector(direction, gravity);
        }
    }
}

function hitTestAngle(shape: Sprite, xPos: Number, yPos: Number, radius: Number): Number
{
    var samples: uint = Math.abs(radius * Math.PI);
    const PI2: Number = Math.PI * 2,
    SAMPLE: Number = 1 / samples;
    var dx: Number, dy: Number, a: Number, tx: Number = 0,
        ty: Number = 0,
        hits: int = 0;
    var i: int = samples;
    while (i--)
    {
        a = PI2 * (i * SAMPLE);
        dx = radius * Math.cos(a);
        dy = radius * Math.sin(a);
        if (shape.hitTestPoint(xPos + dx, yPos + dy, true))
        {
            hits++;
            tx += dx;
            ty += dy;
        }
    }
    if (!hits)
        return NaN;
    return Math.atan2(ty, tx) * (180 / Math.PI);
}

AS3 - delays between addEventLisener and moving an Object

I have a project in which I call a class 3 times named Enemy like this:

public class Main extends MovieClip
{       
    //Enemy 
    private var _Enemy:Enemy;
    private var enemies:Vector.<Enemy> = new Vector.<Enemy>();

//main public

private function init(e:Event = null):void 
{
    removeEventListener(Event.ADDED_TO_STAGE, init);
    setEnemies(3);  //call 3 times          
}


private function setEnemies(numbers:Number):void
{
    for (var i:int = 0; numbers > i; i++)
    {
    _Enemy = new Enemy();       
    addChild(_Enemy);
    //_Enemy.isAlive = true;
    enemies.push(_Enemy);

    }

}

Here's the key contents of enemy:

public class Enemy extends Sprite 
{   

    private var randomX:Number = 1;
    private var randomY:Number = 1;

    public function Enemy()  
    {

        var _BlackFoe:BlackEnemy = new BlackEnemy; 
        addChild(_BlackFoe); // add the bitmap to stage
        SpawnNow();

        addEventListener(Event.ADDED_TO_STAGE, stageAddHandler);

    }

    private function stageAddHandler(e:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, stageAddHandler);
        stage.addEventListener(Event.ENTER_FRAME, MoveNow);

    }



    public function MoveNow(event:Event):void
    {
            x += randomX;
            y += randomY;
            //trace(randomX, randomY);
            if (x >= 780 || x <= 20 ) // Check 2 conditions sepreatly: Enemy x is bigger than the stage's width(800) - 20 ? (x>780) | Enemy x smaller than the stage's width + 20? (x<20)
            {   
            randomX = randomX * -1;
            //trace("Changing X to: " + randomX);
            }   

            if (y >= 580 || y <= 0 ) 
            {   
             randomY = randomY * -1;
             //ce("Changing Y to: " + randomY);
            }   

    }

    public function SpawnNow():void
    {

        var Random:int = 50 + Math.floor( Math.random() * 730 ) 
        x = Random; 
        y = 30;

    }

Well it's pretty simple, 3 enemies start at random positions and bump on to borders and change directions (*-1). BlackEnemy, which is their image, is a class inside a swc library, made and compiled by Flash Pro 6. it's just a small ball. the registration point of it starts in the middle if it matters.

Problem is, they start rather smoothly, then you can see them lagging a bit, sort of dancing while keep moving, then a second after you see them running smoothly again, and the problem repeats itself.

I tried placing faster timers instead of ENTER_FRAME event, but I can still see some lagging. I also tried setting the configuration of FlashDevelop to release mode instead of debug and it didn't help too. If I could share the entire code somewhere so you'd see the swf I will, but for now on I hope this code alone helps... Thank you for your time.

Exact clone of a TextureMaterial

I want to clone a TextureMaterial, modify it and keep the original and the clone for later use.

What I did so far is following:

var BT:BitmapTexture = defaultMaterial.texture as BitmapTexture;
var BD:BitmapData = BT.bitmapData;
var clone:BitmapData = BD.clone();
var newBT:BitmapTexture = new BitmapTexture(clone);
transparentMaterial = new TextureMaterial(newBT, false, true);
transparentMaterial.lightPicker = defaultMaterial.lightPicker; 

but it is not a full copy, because the cloned TextureMaterial does not look like the original. Can anyone help me with that problem please?

I also posted my problem here with an additional image as attachment: http://ift.tt/1jkOFIP

Error in Drag and Drop quiz done of Flash

I am trying to create a drag and drop game on flash. But i end up got one error, syntax error of #error1083,else is unexpected. The error shows at the line 42, and i dont have any idea which line should i did mistake.

Can someone tell me what is wrong with the code?

Here is the codes

    import flash.events.MouseEvent; 
    var objectoriginalX:Number;
    var objectoriginalY:Number;

    blue.buttonMode = true;
    blue.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
    blue.addEventListener(MouseEvent.MOUSE_UP, dropObject);




    green.buttonMode = true;
    green.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
    green.addEventListener(MouseEvent.MOUSE_UP, dropObject);


    red.buttonMode = true;
    red.addEventListener(MouseEvent.MOUSE_DOWN, pickObject);
    red.addEventListener(MouseEvent.MOUSE_UP, dropObject);

    function pickupObject(event:MouseEvent):void
    {
        event.target.startDrag();
        event.target.parent.addChild(event.target);
        objectOriginalX = event.target.x;
        objectOriginalY = event.target.y;
    }

function dropObject (event:MouseEvent):void
{
    event.target.stopDrag();
    var matchingTargetName:String = event.target.name + "target" ;
    var matchingTarget: DisplayObject = getChildByName(matchingTargetName);

    if(event.target.dropTarget != null && event.target.dropTarget.parent == matchingTarget);

{
    event.target.removeEventListener(MouseEvent.MOUSE_DOWN,pickupObject);
    event.target.removeEventListener(MouseEvent.MOUSE_UP,dropObject);
    event.target.buttonMode = false;
    event.target.x = matchingTarget.x;
    event.target.y = matchingTarget.y;
}



    else { // here is where i got error 1083
            event.target.x = objectOriginalX;
            event.target.y = objectOriginalY;
        }
    }

vendredi 25 septembre 2015

AS3 landing smoothly under affect of Gravity

I'm attempting a to make a Fighting game with multiple platforms. I've currently successfully made the controls, movement, (double)jumping, and gravity parts of the game.

My problem is, when a player jumps (more visible when the player Double jumps), when they reach the ground, they seem to go a bit deeper than they should on the platform (they should land and stay on the surface of the platform).

I know why this happens; it's because sometimes hitTestObject takes a while to react when objects come in too quickly.

So, the first thing I thought up is to make the player's foot's y axis equal to the y axis of the top of the platform he lands on.

The problem is; that solution resulted in a rather jerky landing.

So, my question is; Is there a way to make the player to land smoothly on the top surface of the platform?

Some things I've tried:

-Raising FPS, it just made the same effect happen, but more quickly.

-Decreasing the speed at which the player falls, but that makes the game less fun, so I'm crossing it out.

And here's my Code:

Gravity and Jumping:

stage.addEventListener(Event.ENTER_FRAME, loop);
var jumpConstant:Number = 30;
var gravityConstant:Number = 1.8;
function loop(e:Event):void //happens 
{
    if(player.leg1.foreleg1.foot1.hitTestObject(platforms.ground)||player.leg2.foreleg2.foot2.hitTestObject(platforms.ground)) //if either of the player's legs are colliding with the platform [ps: nested movieclips]
    {
        player.ySpeed = 0; //the player stops going downwards
        player.y = platforms.y; //the player's y becomes the platform's y. don't worry, it puts the player in the right place, just not smoothly.
        if (player.b_up) //if Up control button (W or Up Arrow) is being pressed
        {
            player.ySpeed = -player.jumpConstant; //make the player jump

        }
    else //if the player isn't colliding with the platform
    {
        player.ySpeed += player.gravityConstant; //the player is affected by gravity and is pulled downwards
    }

It has more code than that, but that's all that's relevant.

Link to the game if you wanna try it out to see the jerky effect:

http://ift.tt/1KzXZRX

Thank you in advance :)

Easiest way to implement a game menu in ActionScript 3?

At the moment my game simply consists of a play button which, when clicked, runs the game; all of this happens in the document class as follows:

stage.addChild(playBtn);
playBtn.x = 0;
playBtn.y = stage.stageHeight/2;;
playBtn.addEventListener(MouseEvent.CLICK, playGame);

The playGame() function then removes playBtn from the stage and the event listener, and runs the game code. This has been fine for me up until now, but now I want to implement a more complex menu system, which will probably consist of many buttons, graphics, etc (basically a stage select screen). My question is, what would be a more efficient way of displaying a menu on the screen, removing it when a stage is selected and then being able to return to the menu when the game is over? Obviously I'm trying to do all of this without the use of the timeline.

AS3 Create online database

I am creating an android app in as3. I need a free online database to create a login system, where I can save the users username and password along with saved data of the user. I think the app will have a good number of users, so I need a database that works fast. I tried MAMP, but it creates local server, so I need to open the software to use the database from the app. But I need a database that I can access from anywhere, anytime.

How can I get a free online database for my android app?

"Flex users will need to download the original AIR SDK without the new compiler."?

I am confused about upgrading AIR for use with Flex 4.6 (I am using 4.6 because "design mode" isn't supported in Flash Build with later versions).

I successfully overlaid AIR 19 on a copy of the Flex 4.6 SDK. Some projects were fine but others were not. For example the <mx:Alert/> is not supported (apparently) in AIR 19 by default and I resolved that by linking to the mx.swf

In another project I am finding that <s:ConstraintRow/> is not supported. Searching around I found this question: Could not resolve <s:Sequence> to a component implementation after adding AIR 3.6

So, ok – I see the note I missed before on the AIR 19 page: "Flex users will need to download the original AIR SDK without the new compiler."

My Questions:

  • What is the "original" AIR SDK? What version is that? Is this just poor wording and means "the latest AIR without the AS compiler 2.0" Or is Flex deadended for AIR upgrades?
  • What is the deal with AIR version numbers? I see both "AIR 19" and "AIR 3.4" etc. which seems like two different numbering schemes.

SoThink decompiler

I came across something called a SoThink decompiler. It claims to be able to decompile any swf file to fla. if that is true, any program can be plagiarized. I downloaded a trial version and and tried decompiling a few of my projects. while all the assets were seen in the decompiled fla file, it said that the .as files can be made only in a licensed version. if anyone has experience in this can you let me know if all my program is at risk at a cost of 50$ or is there a way to protect it?

Get string value from other class in as3

In my AS3 project, i have two classes named class 1 = Startup.as class 2 = Main.as

In Startup.as, i have this following code

static public var gameInstance:Startup = null;
public var multiplier:Number;
public var path:String;

function name():void{
multiplier = 2;
path = "String value";
Startup.gameInstance = this;
}

In Main.as

var num:Number;
function name(){
num = Startup.gameInstance.multiplier;
trace(num);
trace(Startup.gameInstance.path);
}

I Could get integer values, but not the string values.

Thanks in advance.

jeudi 24 septembre 2015

Make movieclip visible true or false with xml

Trying to make a movieclip visible or not through XML. This is the line of code I am using and it throughs up a whole page of errors.

item1_mc.visible = myXML.children()[0].children()[0];

What is the proper syntax

AS3 IOErrorEvent.IO_ERROR event not catching if file doesn't exist

This doesn't make any sense. I'm trying to load a simple text file. If the file name is just "jeffaberle.txt" then it works fine because that file exists in the location specified. However if the name is changed to "jeffaberle2.txt" the code produces an error because this file does not exist on the server.

I want the IOErrorEvent to fire if the file is missing, but it doesn't fire. There's clearly something I'm missing. Any suggestions?

import flash.events.*;
import flash.net.URLRequest;
import flash.net.URLLoader;

var urlRequest:URLRequest = new URLRequest("http://ift.tt/1MLQYRT" + "?" + Math.random());  // + Math.random()
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

urlLoader.load(urlRequest);

function completeHandler(e:Event):void {
    if (urlLoader.data.trialversion == "true") {
        trace("true");
    } else {
        trace("false");
    }
}
function ioErrorHandler(e:IOErrorEvent):void {
    trace("ioErrorHandlerJeff: " + e.toString());
}

Compiling AS3 program issue with .ttf file in library

I am getting an error trying to compile an AS3 project:

Error: Unable to transcode ../lib/Arial.ttf.

Original Code:

[ Embed(source= "../lib/Arial.ttf", fontName = "ArialFont", advancedAntiAliasing="true", embedAsCFF="false", fontWeight = "bold", mimeType="application/x-font")]
    private var ArialFontClass:Class;

I know very little AS3 so was hoping this was any easy fix with respect to font types or that someone could at least point in a direction to investigate.

Do I need to find a particular folder and look for a file? If I don't have it where do I get it? Any guidance greatly appreciated.

An analogue of the game "Worms". Physics. as3

Help please write a function of the projectile bounce off the ground. How do I find the angle of the collision, and what should be the reflection angle or at least learn the point of collision?

package {
    import flash.display.Sprite;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.BlendMode;
    import flash.geom.Point;
    import flash.geom.Matrix;
    import flash.events.Event;
    import flash.events.MouseEvent;
    public class worms extends Sprite {
        public var terrain_bmpd=new BitmapData(550,200,true,0xFF00FF00);//This is the Bitmap of the terrain
        public var terrain_bmp=new Bitmap(terrain_bmpd);//and this the BitmapData
        public var character=new Sprite();//The character will work as a worm
        public var hole=new Sprite();//That's the hole we need
        public var hole_matrix:Matrix;//The hole_matrix is used to set the position of the hole
        public var left_foot:Point;
        public var right_foot:Point;//These are the feet of the character. We will use it to check collisions
        public function worms() {
            draw_objects();//This function draws the character, the terrain and the hole.
            stage.addEventListener(Event.ENTER_FRAME,fall);
        }
        public function fall(e:Event) {
            /*This function will move down the character if there isn't a collision
            between the terrain and the "feet" of the character*/
            for (var i:int=0; i<10; i++) {//We want to check every pixel if there's acollision, so we won't move the character 10 pixels all at once
                left_foot=new Point(character.x-5,character.y+10);
                right_foot=new Point(character.x+5,character.y+10);
                if (!(terrain_bmpd.hitTest(new
                Point(terrain_bmp.x,terrain_bmp.y),0x01,left_foot))&&!(terrain_bmpd.hitTest(new Point(terrain_bmp.x,terrain_bmp.y),0x01,right_foot))) {
                    character.y++;//If there aren't any collisions, make the character fall one pixel
                }
            }
        }
        public function draw_objects() {
            terrain_bmp.y=200;//The terrain shouldn't be at the top of the stage!
            stage.addChild(terrain_bmp);//We can make the terrain visible
            character.graphics.beginFill(0x0000FF);//Let's draw the character. It will be a blue rectangle.
            character.graphics.drawRect(-5,-10,10,20);
            character.x=250;
            stage.addChild(character);
            hole.graphics.beginFill(0x000000);//Now we draw the hole. It doesn't matter the colour.
            hole.graphics.drawCircle(0,0,30);
        }
    }
}

Is actionscript a good choice for POS?

Since actionscript is my favourite programming language which I also have a lot of experience, would like to know if it's a good choice for a Point of Sale system (Coffe shop, Bar, printing a receipt etc), for a desktop version. Btw I use Adobe Flash CS3. This is my first time trying actionscript for desktop program.

Is there any risk I should know of?

Is there maximum number of states in a component

One of my component already has 9 states and I add one more to it.

It works well when I debug but this component is not working in a right way when I deploy the release version swf. And it shows like this component is in a wrong state.


What quite confuses me is that the debug version swf works well while release version one fails.

And after I rollback the codes it works well again.


So I guess that the translater has done something wrong when I try to release the swf. Maybe there exists a maximum of states for release version?

How to stop an effect from one frame to continue in the next?

I have made a program in which small green rectangles (or Greeny here) are periodically generated at the bottom of the screen and inside the movie clip symbol, I have made a classic tween such that it moves to the top of the screen. I have also declared a variable (t) that increments itself periodically (I am running it at 24 fps). When the value variable, t reaches or exceeds 96, it moves to the next frame. The problem however is that even in the next frame, the generation of these small green rectangles do not stop. Please do excuse me if I have asked the question wrongly. By the way the code on frame 2 is just stop();. Here is the code for frame 1-

var c:int;
var t:int = 0;
var s:int = 8;
function eFrame(event:Event):void
{
    t++;
    if (t%s == 0)
    {
        var i:Greeny = new Greeny  ;
        i.x = Math.random() * 550;
        i.y = 400;
        stage.addChild(i);
    }
    if (t > 96) {
        nextFrame();
    }
}
this.addEventListener(Event.ENTER_FRAME, eFrame);
stop();

Checkbox not checked in dropdown itemrendere flex

I have DropDownlist which have Itemrenderer like following:

<s:DropDownList dataProvider="{testList}" labelField="test" 
                        itemRenderer="DropDownSelectRenderer"/>

ItemRenderer:

<s:ItemRenderer xmlns:fx="http://ift.tt/rYUnH9" 
                xmlns:s="library://ns.adobe.com/flex/spark" 
                xmlns:mx="library://ns.adobe.com/flex/mx" >

<fx:Script>
        <![CDATA[

            protected function onChange(event:Event):void
            {
                trace("checked");
            }

        ]]>
    </fx:Script>

<s:CheckBox id="chkBox" selected="{data.selected}" change="onChange(event)"  />
<s:Label id="lblCon" fontSize="14" text="{data.test}"  />

</s:ItemRenderer>

I want CheckBox change and label click event.
But When i open Dropdown and try to click on checkbox. DropDown is closed(no worry) and checkbox is not checked.

Any help is appreciated.

Loader is returning a null object in as3

I am trying to make a menu that calls another swf file when the button is clicked. however, the message returned is- TypeError: Error #1009: Cannot access a property or method of a null object reference. at GameController()

the GameController() given above is the document class of the called "HotAirRises.swf"

the code is given below: package {

import flash.display.MovieClip;
import fl.controls.Button;
import flash.events.MouseEvent;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;

public class MainController extends MovieClip {


    public function MainController() 
    {
        tester.addEventListener(MouseEvent.CLICK, testIt);
        // constructor code
    }
    private function testIt(e:MouseEvent)
    {
        trace("testing");
        var myLoader:Loader = new Loader();                    
        var url:URLRequest = new URLRequest("HotAirRises.swf"); 
        trace(myLoader,url);
        myLoader.load(url,null);
        addChild(myLoader);
    }
}

}

What am i missing here? something to do with the other HotAirRises.swf file? Please Help!

prevent memory leak reuse array collection

I created an air application with a schedule. To populate this schedule with appointment, I launch an httpservice and result is use to populate an array collection. Each time user change week, a new request is sending.

The variable myDataCalendar (array collection) is defined as [Bindable] private var myDataCalendar :ArrayCollection; I try to reuse the same ArrayCollection, but I think making a mistake because memory increase each time, and garbage collector seems not working!

  myDataCalendar = new ArrayCollection();
  myDataCalendar.refresh();

So can you help me to understand memory leak.

Best regards

Unable to add include ANE File in ANT Script

I wanted to create an ANT Script to create build in one click for my Flex Mobile Project. My app using some native extension file(.ane). When I tried to run the ANT script it saying -

An implementation for native extension 'com.example.mobile.extensions.NativeFeature' required by the application was not found for the target platform 

I am using below code to include ane file in ANT Script.

<compiler.external-library-path dir="${basedir}/ane" append="true">   
                <include name="**/*.ane"/>   
            </compiler.external-library-path> 

Also added the same extensionId in myApp-app.xml file which I used in my extension.xml file.

mercredi 23 septembre 2015

as3 slope detection for non uniform terrains

I want to create a 2d game in which a car moves along the edge of an irregular shaped hill. I want to use basic as3 (no physics engine like Box2d or Nape). With a lot of research I found this thing which is exactly what i want but there is only the logic and no source code. Can someone help me with a piece of code that can do this in as3? Also suggest if there is a better alternative to get the desired output.

URGENT HELP AS3 Client Server Socket how to connect/run?

Okay so I know this is probably a stupid question, but how do i actually run this client/server project on actionscript 3? I'm using flashbuilder. I'm not sure if i'm even doing the right thing, i made a new as mobile project and put in the code for my client which is this:

public class client extends Sprite
{
    private var socket:Socket;
    private var IP:String = "127.0.0.1";

    public function client()
    {
        super();

        socket = new Socket();
        socket.addEventListener(Event.CONNECT, onConnected);
        socket.connect(IP, 5555);
    }

    protected function onConnected(event:Event):void
    {
        socket.writeUTFBytes("communication between Sockets (Client socket and server socket)");
        socket.flush();
    }
}

and then i made a new class within the package that has the client class (as above) in it and put in this as the server class:

public class NewSocketServerTest extends Sprite
{
    private var serverSocket:ServerSocket = new ServerSocket();
    private var clientSocket:Socket;

    private var txt:TextField;
    public function NewSocketServerTest()
    {
        createUI();
        serverSocket.bind(5555);
        serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onConnected);
        serverSocket.listen();
    }

    protected function onConnected(event:ServerSocketConnectEvent):void
    {
        txt.appendText("This is a demonstration of \n" );
        clientSocket = event.socket;
        clientSocket.addEventListener(ProgressEvent.SOCKET_DATA, onDataHandler);
    }       

    protected function onDataHandler(event:ProgressEvent):void
    {
        var str:String = clientSocket.readUTFBytes(clientSocket.bytesAvailable);
        txt.appendText(str);
    }

    private function createUI():void
    {
        txt = new TextField();
        txt.width=400;
        txt.height=400;
        txt.appendText("Hello! \n");
        addChild(txt);
    }
}

when i try run this in an emulator it's just a white screen and i'm not sure what i'm doing wrong.. please help i am so desperate to get this working as it is for a class activity and it is very urgent!

AS3 - Shooting Game - hitTestObject

i'm about to finish my project for University. But I'm stuck with the hittestobject.

var Player: gun = new gun();
Player.x = mouseX;
Player.y = mouseY;
addChild(Player);

stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot);
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot);

function mousemove(e: MouseEvent): void
{
        Player.x = mouseX + 200;
        Player.y = mouseY + 35;
}

function shoot(event: Event): void
{
        var Bullet: bullet = new bullet();
        /*var explosion:explo1 = new explo1(); */
        Bullet.x = Player.x;
        Bullet.y = Player.y;
        /*      explosion.x = Player.x;
                explosion.y = Player.y;*/
        Player.rotationX = 5;
        Player.rotationY = 5;
        addChild(Bullet);
        /*      addChild(explosion);*/
        Bullet.addEventListener(Event.ENTER_FRAME, moveBullet);
}

function release_shoot(event: Event): void
{
        var explosion: explo1 = new explo1();
        Player.rotationX = -5;
        Player.rotationY = -5;
}

function moveBullet(e: Event): void
{
        e.target.y -= 12;
        e.target.x -= 96;
        if (e.target.y <= -200 || e.target.x <= -200)
        {
                e.target.removeEventListener(Event.ENTER_FRAME, moveBullet);
                removeChild(MovieClip(e.target));
        }
}

function goesside_1(event: Event): void
{
        mc_target.x -= 2;
        if (mc_target.x < -20)
                mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);

function targeting(event: Event): void
{
        var bullet: MovieClip = MovieClip(event.target);
        if (bullet.hitTestObject(mc_target))
        {
                mc_burst.x = mc_target.x;
                mc_burst.y = mc_target.y;
                mc_burst.gotoAndPlay(2);
                mc_target.x = 200;
                mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
                mc_target.x = 200;
                trace("targerting");
        }
        else if (mc_target.x > 550)
                bullet.removeEventListener(Event.ENTER_FRAME, targeting);
        else
                bullet.y -= 12;
        bullet.x -= 96;
}

The bullet is going in the Target without any doubt, I see it haha... But won't replace mc_target with mc_burst.

EDIT

This is the working code I used for anyone who's interested:

var Player:gun = new gun(); 
Player.x = mouseX; 
Player.y = mouseY; 
addChild(Player); 

stage.addEventListener(MouseEvent.MOUSE_MOVE, mousemove); 
stage.addEventListener(MouseEvent.MOUSE_DOWN, shoot); 
stage.addEventListener(MouseEvent.MOUSE_UP, release_shoot); 
function mousemove(e:MouseEvent):void{ 
Player.x = mouseX + 200; 
Player.y = mouseY + 35; 
} 

function shoot(event:Event):void{ 
var bullet1:bullet = new bullet();
/*var explosion:explo1 = new explo1(); */
    bullet1.x = Player.x;
    bullet1.y = Player.y;
/*  explosion.x = Player.x;
    explosion.y = Player.y;*/
    Player.rotationX = 5;
    Player.rotationY = 5;
    addChild(bullet1); 
/*  addChild(explosion);*/
    bullet1.addEventListener(Event.ENTER_FRAME, targeting); 
} 

function release_shoot(event:Event):void{ 
var explosion:explo1 = new explo1(); 
    Player.rotationX =- 5;
    Player.rotationY =- 5;

}

function movebullet(e:Event):void{ 
e.target.y -= 12;
e.target.x -=96;/*When the function is called the targets Y position will be subract by 40 pixels every frame, this makes the movieclip move up. The target is the Bullet movieclip.*/
if(e.target.y <= -200 && e.target.x <= -200 ){ 
e.target.removeEventListener(Event.ENTER_FRAME, movebullet);
removeChild(MovieClip(e.target));
}
}
function goesside_1(event:Event):void {
    mc_target.x -= 2;
        if (mc_target.x < -20)
        mc_target.x = 550;
}
mc_target.addEventListener(Event.ENTER_FRAME, goesside_1);

function targeting(event:Event):void {
    var bullet1:MovieClip = MovieClip(event.target);
    if (bullet1.hitTestObject(mc_target)){
        mc_burst.x = mc_target.y;
        mc_burst.y = mc_target.x;
        mc_burst.gotoAndPlay(2);
        mc_target.x = 200;
        mc_target.removeEventListener(Event.ENTER_FRAME, targeting);
        mc_target.x = 200;
        trace("targerting");
    } 
    else if (mc_target.x > 550){
        bullet1.removeEventListener(Event.ENTER_FRAME, targeting);
    }
    else{
    bullet1.y -= 12;
    bullet1.x -= 96;}

}
// REPLACING CURSOR BY A SIGHT //

import flash.ui.Mouse;

Mouse.hide();

var myCursor:sight = new sight();

myCursor.visible = false;

function init()
{
    addChild(myCursor);
    stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
    stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
    stage.addEventListener(MouseEvent.ROLL_OVER, mouseLeaveHandler);
    stage.addEventListener(MouseEvent.ROLL_OUT, mouseMoveHandler);

}

function mouseMoveHandler(evt:MouseEvent):void
{
    myCursor.visible = true;
    myCursor.x = evt.stageX + 10;
    myCursor.y = evt.stageY + 10;
}

function mouseLeaveHandler(evt:Event):void
{
    myCursor.visible = false;
}
init();