mardi 31 janvier 2017

AS3 - Flash - CS6 Create Nested MovieClip on the fly and add it to the stage

ball:Ball is a MovieClip
trail:Trail is a MovieClip

ball = new Ball(speedX, speedY);

trail, contains a ball. trail, is a defined sized of stage. ball, inside trail, has a Tween that follows a Defined path.

//The problem
trail = new Trail();
Error:

ArgumentError: Error #1063: Argument count mismatch on Ball(). Expected 2, got 0. at flash.display::Sprite/constructChildren()

It took me a while to consider. I am creating a new instance of Trail, and inside of Trial is a Ball already. Isn't the Ball already created inside Trail when I designed the nested MovieClip Trail? Thus the error and not knowing how to resolve it; as the Ball inside is already in place and Tweening.

Setup: Nothing on stage. No MovieClips. It's all created and added to the stage at run-time. Balls are already on stage before this error adding an instance of Trail at run-time.

Adobe AIR multi platform Unique ID (Hardware ID)

How to get an unchangeable unique ID for make licensing system in new Adobe AIR (ActionScripts3) for multi platform?

If there is no default way in AIR development system, what's best copy protection way for AIR platform?

Drag and Drop actionscript outputs

I am doing a drag and drop game wherein if you put the symbol at the target you will gain points and if you put a symbol at the wrong target you will get a deduction on your score. the problem is if ever i put a symbol wherever except the right target it keeps deducting the score. here's the code

stop(); 
var currency:int = 100; 


var objectoriginalX:Number;
var objectoriginalY:Number;
currencytxt.text = currency  + "";
symbol1.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol1.addEventListener(MouseEvent.MOUSE_UP, dropObject);                    


symbol2.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol2.addEventListener(MouseEvent.MOUSE_UP, dropObject);          


symbol3.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol3.addEventListener(MouseEvent.MOUSE_UP, dropObject);          


symbol4.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol4.addEventListener(MouseEvent.MOUSE_UP, dropObject);      


symbol5.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol5.addEventListener(MouseEvent.MOUSE_UP, dropObject);      


symbol6.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
symbol6.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 = "target" + event.target.name;
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;
     currency = currency + 100; 
     currencytxt.text = currency  + "";
    }
else if(event.target.dropTarget != null && event.target.dropTarget.parent != matchingTarget)
{
    event.target.x = objectoriginalX;
    event.target.y = objectoriginalY; 
     currency = currency - 100; 
     currencytxt.text = currency  + "";
}

 else 
    {
    event.target.x = objectoriginalX;
    event.target.y = objectoriginalY;  
    }
} 

What's the easiest way to store preferences data in cross platform AIR application?

I'm new Adobe Animate programmer, I like to ask experienced ActionScripts 3 developers, Is there any default and simple way to store preferences in ActionScripts like UNITY3D ? or not what is easiest way that works without modification for cross platform?

1.Text file. 2.XML file. 3.JSON file. 4...?

Adobe AIR Android XML Write Read issue

I tried to test blow code on android device but i couldn't see any data to text fields. This code works well on AIR Desktop but in android no. Is it difference between AIR FileStream function on Desktop and Android? Whats best cross platform code to save files and read write?

import flash.filesystem.*;

             var prefsFile:File; 
            [Bindable] var prefsXML:XML; 
             var stream:FileStream; 

             function appStart():void
            { 
                prefsFile = File.applicationStorageDirectory;
                prefsFile = prefsFile.resolvePath("preferences.xml"); 
                readXML();
            }


             function readXML():void 
            {
                stream = new FileStream();
                if (prefsFile.exists) {
                    stream.open(prefsFile, FileMode.READ);
                    processXMLData();
                }
                else
                {
                    saveData();
                }

            }


             function processXMLData():void 
            {
                prefsXML = XML(stream.readUTFBytes(stream.bytesAvailable));
                stream.close();
                trace(prefsXML.Data1);
                trace(prefsXML.Data2);
                trace(prefsXML.Data3);
                txt_D1.text = prefsXML.Data1;
                txt_D2.text = prefsXML.Data2;
                txt_D3.text = prefsXML.Data3;

            }


             function windowClosingHandler(event:Event):void 
            {
                saveData();
            }


             function saveData():void
            {
                createXMLData(); 
                writeXMLData();
            }


             function createXMLData():void 
            {
                prefsXML = <preferences/>;
                prefsXML.Data1 = 1;
                prefsXML.Data2 = 2;
                prefsXML.Data3 = 3;
            }


             function writeXMLData():void 
            {
                var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';
                outputString += prefsXML.toXMLString();
                outputString = outputString.replace(/\n/g, File.lineEnding);
                stream = new FileStream();
                stream.open(prefsFile, FileMode.WRITE);
                stream.writeUTFBytes(outputString);
                stream.close();
            }

appStart();

AS3 Security.showSettings() not always shows dialog in FF

I call Security.showSettings(SecurityPanel.PRIVACY) in my AS3 script and it always shows dialog in Chrome, but in Firefox it only works when I place my file.swf directly on the html page. Nothing happens when I insert it dynamically via swfobject.js(v2.2) and after some time try to open security panel.

Lately this worked fine in both browsers. Is there some trick?

exe created from mBlock source code gives not a valid win32 application

I am trying to compile the mBlock source code from github (http://ift.tt/2kOZKm8)

I followed all the steps that are present in the tutorial from mBlock in 'HOW TO COMPILE MBLOCK'.

My problem is that mblock runs in the 'Debug Mode' in Flash Builder 4.7 (Trial version). But when I export the release build, with 'native installer' or 'captive runtime' option, then running the executable gives error that '[application name] is not a valid win32 application'

I have tried that on 3 different laptops. On all three laptops (each has x64 bit architecture), the mblock code compiles and runs perfectly in the Debug mode but when export the build, it gives 'win32 application' error.

Thank you

AGAL seq opcode works on hardware, but doesn't on software emulation (float number comparison is different on both?)

From docs: seq set-if-equal destination = source1 == source2 ? 1 : 0, component-wise

I haven't yet tested it thoroughly, but so far my fragment shader worked on both machines (desktop pcs), where context3D initialization succeeded as DirectX, but doesn't work on machines where flash falls back to software rendering.

seq ft2.x, ft0.x, fc0.x

ft.x is set to 1 on hardware, when current pixel red value, stored in ft0.x is equal to constant fc0.x, which stores 50/255. So what I want to happen, does happen on #32???? (50 == 0x32) colored pixel on hardware, but doesn't on software.

I already tested for a workaround, and I can replace seq opcodes with a more complex algorithm involving slt (set if less than) or sge (set if greater or equal).

So it seems the problem lies in a comparison of a constant I supply to the GPU (50/255) and the actual red value (which is 50 in the texture). If it was anything else (e.g. RGBA values had a different order), slt and sge would fail as well.

Am I doing something wrong here? Should I somehow round compared values (e.g. multiply by 255 then remove the fractional) in order to be sure it will work in all devices and modes?

lundi 30 janvier 2017

How to save video file in ios camera roll using as3?

I need help to save video files in ios camera roll using as3. Do you know any way or an ANE that can cater this requirement? Appreciate your help. Thanks

animating a hero with on double key press as3

Im an novice/intermediate AS2 coder.I just starting to work in AS3 (Flash Pro Cs6) and Im creating a space shooter. Im trying to figure out how I can code my fighter with a movie clip (muzzle flash) when spacebar and a directional key are pressed at the same time. Again, please help, Im a nubie with AS3 and im really struggling with this.

In flash as3 webcam how to get newly connected webcam name at run-time?

I have a flash as3 based webcam video recorder that publishes the webcam video stream and to do this i am using the following codes :

var camera:Camera = Camera.getCamera(0);
var arr:Array = Camera.names;
if(camera != null)
{
    videoWidth = topBorderContainer.width;
    videoHeight = topBorderContainer.height;
    camera.setMode(videoWidth, videoHeight, 30, false);
    camera.setQuality(0, 100);
    if (camera)
    {
        videoDisplay.videoObject.attachCamera(camera);
    }
}

But problem is that if i am connecting a new document camera at run time and running my webcam tool then Camera.names returning the previously connected document camera name instead of returning the new document camera name.

And to get new document webcam name i have to restart my application again.

But i have no knowledge how to get newly connected document camera name at run time so if anybody know how to get the newly connected document camera name at run time please help me to solve.

AS file for begin from different frame

I have a timer code.I wanna start of new timer when player has choosing start at specific frame(level).I write AS,I make search for using event listener on package but I can't figure out to how translate that from to class code.

This is orginal code

var minute:Number = 0;
var second:Number = 16;
 
//This timer check to timer and set to what happen if time over.
var timercheck:Timer = new Timer(1000,0);
timercheck.addEventListener(TimerEvent.TIMER, timercheck1);
timercheck.start();
 
function timercheck1(evt:TimerEvent):void {
if (minute <1 && second <1)
{
timer.stop();
timeisup.visible = true;
timeisup.play();
} 
 
}
timeisup.visible = false;
// Create the timer
// Checks the clock function every 1000 milisecond (1 second)
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, clock);
timer.start();
 
// Function that increments the timer

function clock(evt:TimerEvent):void {

// every time this function is checked increment second by one
second -= 1;
 
// If the second is 59
if(second < 0){
// The minute will be plussed with 1
minute -= 1;
//and the zero will be set to 00
second = 59;
}
 
var time:String = minute + ":" + prependZero(second);
sctuts.text = time;
}
 
function prependZero(num)
{
if(num<10)
{
num="0"+num; //Add zero to second if less than 10
}
return(num);
}

And I writing as but I'm not sure goes correct.

package  {
 import flash.utils.Timer;
 import flash.events.TimerEvent;

public class timertick {

    static public var minute:Number = 2;

    static public var second:Number = 0;

    static public var timercheck:Timer = new Timer(1000,0);

    static public var timer:Timer = new Timer(1000);

    static public var time:String = minute + ":" + prependZero(second);

    public function timercheckbasla():void {
        timercheck1 = new Timer(1000,0);
        timercheck1.addEventListener(TimerEvent.TIMER, onTimer);
        timercheck.start();
    }

    // Create the timer
    // Checks the clock function every 1000 milisecond (1 second)
    public function timer():void {
        timercheck1 = new Timer(1000,0);
        timercheck1.addEventListener(TimerEvent.TIMER, onTimer);
        timercheck.start();
    }


    private function onTimer(e:TimerEvent):void {

            if (minute <1 && second <1)
{
timer.stop();
timeisup.visible = true;
timeisup.play();
} 
 
//I not finished yet

    }

}
}

ActionScripts3 read XML from Server issue

I have a sample XML on LocalHost and I wrote some code to read it's data, it works fine but when i uploaded to Byethost server it works on web-browser but return error in Adobe Animate.

XML Sample:

<?xml version="1.0" encoding="UTF-8"?>
<Data>

    <D1>1</D1>
    <D2>2</D2>
    <D3>3</D3>

</Data>

AS3 Codes:

import flash.events.Event; 
import flash.net.URLLoader; 

var myXML:XML = new XML(); 
var XML_URL:String = "http://ift.tt/2kKJW48"; 
var myXMLURL:URLRequest = new URLRequest(XML_URL); 
var myLoader:URLLoader = new URLLoader(myXMLURL); 
myLoader.addEventListener(Event.COMPLETE, xmlLoaded); 

function xmlLoaded(event:Event):void 
{ 
    myXML = XML(myLoader.data); 
    trace(myXML.D1); 
    trace(myXML.D2); 
    trace(myXML.D3); 

}

Output when reading XML in localhost from ActionScripts3:

1 2 3

Output when using Web-Browser:

1 2 3

Output when reading XML in server (byet.host) from ActionScripts3:

TypeError: Error #1085: The element type "d.length;f++)e+=(16" must be terminated by the matching end-tag "</d.length;f++)e+=(16>".

Flex to HTML : How to convert actionscript

I'm converting a big application in Flash/Flex to HTML5/CSS/JS. I tried to translate AS classes but it's a bit difficult.
Do you know if I can find a JS equivalent to the natives AS classes? Or if there is a reliable converter able to cross every classes of my app?

I can use ES6 format with the tags class, constructor, etc...

Thank's a lot.

samedi 28 janvier 2017

Combine two Javascripts together

Can someone please help me combine these two scripts into one? I have no clue about javascript... I want to perform the same function on two different elements. Any help would be much appreciated. Thank you

{

(function() {

"use strict";
// Run an event when the record list page is displayed
kintone.events.on('app.record.index.show', function(event) {

    //Retrieve an array of field elements of the fields with field code of "Attendance"
    var elStatus = kintone.app.getFieldElements('Schstatus');

    //Change the properties of the retrieved field elements for each record
    for (var i = 0; i < elStatus.length; i++) 
    {
        var record = event.records[i];
        if (record['Schstatus']['value'] === "Call Out") 
        {
            elStatus[i].style.color = 'white';
            elStatus[i].style.backgroundColor = "#e74c3c";

        } 

        else if (record['Schstatus']['value'] === "Pending")
         {
            elStatus[i].style.color = 'black';
            elStatus[i].style.backgroundColor = "#ffcc00";
         }

         else if (record['Schstatus']['value'] === "Confirmed")
         {
            elStatus[i].style.color = 'white';
            elStatus[i].style.backgroundColor = "#a3b815";

         }

    }

});

})();

}

The second script is identical but with a different field....

{

(function() {

"use strict";
// Run an event when the record list page is displayed
kintone.events.on('app.record.index.show', function(event) {

    //Retrieve an array of field elements of the fields with field code of "Attendance"
    var elStatus = kintone.app.getFieldElements('Attendance');
    var elStatuss = kintone.app.getFieldElements('Schstatus');

    //Change the properties of the retrieved field elements for each record
    for (var i = 0; i < elStatus.length; i++) 
    {   var record = event.records[i];
        if (record['Attendance']['value'] === "No-Show") 

    {   elStatus[i].style.color = 'white';
        elStatus[i].style.backgroundColor = 'red';  } 


    else if (record['Attendance']['value'] === "Late")
    {   elStatus[i].style.color = "#a023bc";        }


    else if (record['Attendance']['value'] === "On-Time")
    {   elStatus[i].style.color = 'green';          }

    }

});

})();

}

How to create scrolling list with picture in Adobe Animate CC/ActionScripts3

I'm a designer and animator, I newly start to coding with Adobe Animate CC, In all versions of adobe flash there is List item but i couldn't find a simple way to add image and text to it, if possible guide me how can i make a scrolling list like below sample image (scroll to receive content from server "like a news app") with simple way not complex coding. I prefer to use Adobe Animate not Adobe FlashBuilder/Flex.

Simple suggestions, Link to tutorial, ...

Sample UI

StageWebView wont dispose()

swv.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, swvLocationChange);
            swv.viewPort = null;
            swv.stage = null;
            swv.dispose();
            swv = null;

This is the code that I have to remove the stagewebview. Following previous articles and other stackoverflow posts, it will not go away. I still see a leftover white screen. What do I do? Am I doing it right?

How to open a .fla file which also has .as files in the same folder?

I want to know how to open this file, can someone help me?

Downloaded from : http://ift.tt/2kEnQjB

vendredi 27 janvier 2017

adobe air AS3 :How to run a function in workers_ Multithreading (by Workers)

I have a heavy function that is not proper to be executed in the main timeline (because it takes a long time to be finished and crashes the program ) . therefore I searched for multithreading in air(as3) but all the examples I found has explained how to run separate swf files in workers .how can I run a function in a worker(thread)?

Not access to objects when I start from different frame

Not accessing objects when start of diffrent frame

I creating a game if I start to game at frame 1 everything is ok.But is there many object is not work when player has choice to level from menu and start level 2.(Level 2 is frame 107)

That's all not work because all of codes stay before the frame 107 (level 2)

It's work clearly on level 2 when I use the same object to call another instance name and function.But I have timer and it's should start 2 min when player start level at 2.

Here is problems when player has choice to level 2.

Butons disiplay but not work. High score text not disiplay. Timer not disiplay.

What shold I do ? Is this need a script or something else ?

Convert .swf file to .as

I can convert .as file to .swf on Linux using for example mtasc program. But what should I do to convert .swf file to .as? I can not find any program to do it.

AS3 Accessing Symbols on the IKArmature

I am VERY new to this programming thing, but I am trying to work on a project. My background actually comes from the Game Art side, rather than the Game programming side, so, I hope to come off with a bit of clarity here.

I am trying to make a game in flash and I have built a character using an IKArmature. The symbols that attached to the armature represent the character skins that are going to be changeable. SO the idea is that I am able to change skins on each of the characters while reusing the animations.

The trouble I'm having is accessing the symbol in AS3. I am still learning it, but I have yet to find a tutorial that spells out how to get to the symbol itself, on the armature. I figure I'm just approaching it from an artist's mind instead of a programmer's mind. So, please spell it out for me, in very base terms.

Thank you

How to handle the SecurityError #2070 and #2000 in Loader.load()

I have a AIR project that loads a any swf. But when the loaded swf dispatches a SecurityError, I can't handle this error! My code is bellow:

var loader:Loader = new Loader();

_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, swfErrors);
_loader.contentLoaderInfo.addEventListener(Event.INIT, swfInit);
_loader.contentLoaderInfo.addEventListener(Event.OPEN, swfOpen);
_loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatus);
_loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, swfSecurityError);
_loader.contentLoaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrors);

try {
    _loader.load(new URLRequest('path.swf'));
}
catch(e:SecurityError) {
    trace("trying handle error!");
}

function swfComplete(e:Event):void {
    trace("complete");
}

function swfErrors(e:IOErrorEvent):void {
    trace("swf error: " + e.toString() );
}

function swfInit(e:Event):void {
    trace("swf init");
}

function swfOpen(e:Event):void {
    trace("swf open. this listener dispatch!");
}

function httpStatus(e:HTTPStatusEvent):void {
    trace("http status: " + e.toString() );
}

function swfSecurityError(e:SecurityErrorEvent):void {
    trace("trying handle security error. :(");
}

function uncaughtErrorEvent(e:UncaughtErrorEvent):void {
    trace("uncaught error: " + e.toString() );
}

The exceptions from FlashDevelop:

[Fault] exception, information=SecurityError: Error #2070: Security sandbox violation: caller file.swf cannot access Stage owned by app:/myApp.swf.

[Fault] exception, information=SecurityError: Error #2000: No active security context.

The problem is that my program quits and I can not catch these security errors. How can I prevent my program from closing?

How to remove word "null" from string in ActionScripts3

I have code for convert each 2 numbers to a specific character, this code works, but output is with an unwanted word "null". I want to remove it. I can't identify which part of code is wrong.

var encoded_numbers:String = "102030";
var sub:String;
var decode_string:String;

for (var i2:int = 0; i2 < encoded_numbers.length; i2 += 2) 
{
    sub = encoded_numbers.charAt(i2) + encoded_numbers.charAt(i2 + 1);
    //trace(sub);

    switch(sub) 
   { 
    case "10": 
        decode_string += "A";
        break; 
    case "20": 
        decode_string += "B";
        break; 
    case "30": 
        decode_string += "C";
        break; 

   }

}
trace(decode_string);//convert      

Output string:

nullABC

Convert an API KEY to string of numbers and reverse in ActionScripts3

We need to convert some API KEYs to string numbers and convert that numbers to original string.

Sample API KEY: "ZfIgG9LliwY4cDw4Rqso0m7SEQZovI"

We converted it with our algorithm

var encode_array:Array = "ZfIgG9LliwY4cDw4Rqso0m7SEQZovI".split("");
var encode_string:String;
var count1:int = encode_array.length; var i1:int;
for (i1 = 0; i1 < count1; i1++) 
{ 

    switch(encode_array[i1]) 
   { 
    case "*": 
        encode_string += *;
        break; 
    ...
   }

Converted API KEY:"364219431799224845593594391459942853555190499729152736515819"

Each 2 numbers in this string are related to 1 chracter in API KEY.(Sample: "36" > "Z")

My problem is second part to reverse this (convert each 2 number to defined character), How to possible separate every 2 numbers in this string and save them in an array? I think it possible with RegExp in ActionScripts, but i don't know how.

Actionscript 3: each line from text file as a element in array

So my problem is that trace within the function does trace the first element of the array, but the trace outside if the function does not. I do declare the array variable outside the function, but the data wont save to the array variabel.

var oppgaveLoader:URLLoader = new URLLoader();

oppgaveLoader.load(new URLRequest("oppgaver.txt"));
var oppgaveNr = 0
//store line of text on an array called oppgaver
var oppgaver:Array = []
var oppg:Array = new Array()
oppgaveLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event){
    oppgaver = e.target.data.split(/\n/)
    trace(oppgaver[0]) //This one traces the frist item in the array
}
trace(oppgaver[0])//This one does not trace the first one in the array

Does anyone know why and/or how to fix it if posible? The file "oppgaver.txt" is located in the same directory as my .fla file

The file "oppgaver.txt" is laid out like this (the text is in norwegian, but each line is going to be a item in the array):

Hvor gjelder forbudsskilt hvis ikke annet er oppgitt?
Hvordan foretar du best mulig bremsing og unnastyring?
Hvordan bør du normalt plassere bilen på en vanlig 2-felst vei?

jeudi 26 janvier 2017

Multiplying decimals in Actionscript 3

I'm making a tax calculator for my class and I can't figure out how to multiply a whole number with a decimal. I have to multiply the whole by 0.13. Here's my code

var amount:Number;
var hst:int;

amount_txt.restrict = "0-9";



calculate_btn.addEventListener(MouseEvent.CLICK, calculate);

function calculate(event:MouseEvent):void
{
  amount = Number(amount_txt.text);

total_txt.text = "You have spent a total of " + String(Math.round((amount * hst)) + "$") 
}

I would appreciate help quick, as it is due tomorrow. I apologize if the formatting on here is incorrect, but I assure you on the actual program it is correct. Thanks

Associating Javascript classes/objects with HTML widgets/graphical objects, a la AS3

Please forgive me if this is too general or too poorly conceived. I'm coming from the (now defunct) world of OOP AS3 and would like to bring some of the techniques I learned there for structuring code to my Javascript coding.

One of the nifty things about AS3 was that it was quite easy to associate a Class with an on-screen graphical object, aka MovieClip. There was a one-to-one correspondence between the graphical object and the code. And the you created a new graphical object (new WidgetBot, e.g.) and added it to the stage, it's class (for example event listeners, data structures, etc) was already set up to work with it.

Is this a technique that can easily be brought to the HTML/JS world? That is, does it make sense to, say, associate a DIV with a Javascript class or object? So that one could "place" this DIV on screen (by showing it via CSS or adding the HTML via jQuery) and then it would auto-magically have the event listeners associated with elements "within" that DIV be ready to go? If so, is there a specific technique for doing so?

Again, this may be a non-starter in the JS world, and if so please don't down-vote me -- it was the way to do things in the AS3 world, and it was a great way to keep code organised. I was just wondering whether any of this could be translated here.

How do I authenticate against Firebase

I'm following this guide on how to write to my database with an authenticated user. I have set the rules properly and am able to post if all the writes are true just fine. When I pass the oauthToken I get when I follow this guide I get "Invalid claim "kid" in auth header". I've seen other questions with this result but I don't think they're doing the exact same things as I am nor are they using the same language.

So how do I authenticate properly? I can get the token and everything else just fine.

Current rule set:

{
"rules": {
    "location": {
        "$user_id": {
            ".read": all,
            ".write": "$user_id === auth.uid"
        }
    }
}

}

My code:

    private function submitNewData(localId:String, authToken:String):void
    {
        var data:Object = new Object();
        data.location = "w0.0rld";
        data.description = "hello";

        var request:URLRequest = new URLRequest("https://" + FIREBASE_PROJECT_ID + "http://.firebaseio.com/location/" + uid + ".json?auth=" + authToken);
        request.data = JSON.stringify(data);
        request.method = URLRequestMethod.POST;

        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, entrySent);
        loader.load(request);   
    }

    private function entrySent(event:flash.events.Event):void
    {
        trace(event.currentTarget.data); //Invalid claim 'kid' in auth header
    }

IPA packing for ad-hoc or app store, test version is working

BASETHREADINITTHUNK() RtlUserthreadstart() compliation failed while executing

Hi when i tried to build add-hoc or app store version of IPA, i got this above error.enter image description here

Simple ActionScripts3 JSON send to PHP

I'm trying to send a simple json data "{"DATA1":"111","DATA2":"222"}" to PHP from ActionScripts3, There is no error and warning but nothing happened in PHP.

AS3:

import flash.net.*;
import flash.events.Event;

 function JSON_send():void 
 { 
       var url:String = "http://localhost/as_json_write.php"; 

       var JSON_strings:String = "DATA1="+"111"+"&DATA2="+"222"; 

       var postParams:URLVariables = new URLVariables(JSON_strings);

       var request:URLRequest = new URLRequest(url);
        request.method = URLRequestMethod.POST;
        request.data = postParams;

       var urlLoader:URLLoader = new URLLoader();

        urlLoader.addEventListener(Event.COMPLETE, onLoaderComplete);
        urlLoader.load(request);

}

function onLoaderComplete( event:Event ):void
{
       var urlLoader2:URLLoader = event.target as URLLoader;
}

JSON_send();

PHP:

<?php

ob_start();
var_dump($_POST['myObject']);
print_r($_POST);
$content = ob_get_contents();
ob_end_clean();
$json_data = json_decode($content);
echo $json_data;

?>

Send POST request with custom headers using flash

I am trying to send POST request with custom headers using flash, but I can only get it to send the request as GET even when I use request.method = URLRequestMethod.POST;

Here is my code:

package {
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;

public class URLRequestExample extends Sprite {
    private var loader:URLLoader;

    public function URLRequestExample() {
        loader = new URLLoader();
        configureListeners(loader);
        var url:String = "http://example.com/";
        var headers:Array = [
            new URLRequestHeader("X-CUSTOM-HEADER", "X-VALUE"),
            new URLRequestHeader("Accept", "application/json")
        ];
        var requestVars:URLVariables = new URLVariables();
        requestVars.test = "test";
        request.data = requestVars; // If this line and the one under it are commented the request goes as GET
        request.requestHeaders = headers; // ^with no request headers
        var request:URLRequest = new URLRequest();
        request.method = URLRequestMethod.POST; // Using URLRequestMethod.POST but the request is still sent as GET
        request.url = url;
        try {
            loader.load(request);
        } catch (error:Error) {
            trace("Unable to load requested document.");
        }
    }

    private function configureListeners(dispatcher:IEventDispatcher):void {
        dispatcher.addEventListener(Event.COMPLETE, completeHandler);
        dispatcher.addEventListener(Event.OPEN, openHandler);
        dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
        dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
        dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
    }

    private function completeHandler(event:Event):void {
        var loader:URLLoader = URLLoader(event.target);
        trace("completeHandler: " + loader.data);
    }

    private function openHandler(event:Event):void {
        trace("openHandler: " + event);
    }

    private function progressHandler(event:ProgressEvent):void {
        trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
    }

    private function securityErrorHandler(event:SecurityErrorEvent):void {
        trace("securityErrorHandler: " + event);
    }

    private function httpStatusHandler(event:HTTPStatusEvent):void {
        trace("httpStatusHandler: " + event);
    }

    private function ioErrorHandler(event:IOErrorEvent):void {
        trace("ioErrorHandler: " + event);
    }
}
}

And in my crossdomain.xml file I have:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://ift.tt/1d1B8yI">
<cross-domain-policy>
    <site-control permitted-cross-domain-policies="all"/>
    <allow-access-from domain="*" secure="false"/>
    <allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>

ActionScripts 3 read JSON from PHP issue

I'm trying to read JSON data from localhost PHP in ActionsScripts3, I found some code to do it but this code doesn't works.

PHP:

<?php 
$arr = array ('DATA1'=>"111",'DATA2'=>"222");
header('Content-Type: application/json');
echo json_encode($arr);
?>

AS3:

import flash.display.*;
import flash.events.*;
import flash.net.*;


var urlLoader:URLLoader=new URLLoader();

function ReadJsonPhp () :void
        {
            addEventListener(Event.ADDED_TO_STAGE,init);
        }

function init(event:Event)
        {
            urlLoader.load(new URLRequest("http://localhost/asphp.php"));
            urlLoader.addEventListener(Event.COMPLETE, urlLoaderCompleteHandler);
        }
function urlLoaderCompleteHandler(e:Event):void 
        {
            trace(e.target.data) ;
            var arrayReceived:Object = JSON.parse(e.target.data);
        }

ReadJsonPhp();

This code have 3 function if possible i like to use only 1 function.

mercredi 25 janvier 2017

I need a working pause and resume code on my project

I tried many of code so for pause and play to game but did not work many of them.

I got a moving object on stage also I have timer dynamic text.

I need a working pause and play code on my project.

Example my moving object

/*Fish 3 move*/
var balik3x:Number=7;
var balik3y:Number=Math.random()*15
 
stage.addEventListener(Event.ENTER_FRAME,h3);
function h3(oly:Event) {
balik3.x+=balik3x;
balik3.y+=balik3y;
if ((balik3.x>=stage.stageWidth-balik3.width/2)|| (balik3.x <= balik3.width/2 )) {
    balik3x*=-12;
}
if ((balik3.y>=stage.stageHeight-balik3.height/2)|| (balik3.y <= balik3.height/2 )) {
    balik3y*=-1;
}
}
balik3.mouseEnabled = false;

My timer code

time.text="0:10";
var dispSecs=09;
var dispMins=0;
 
var timerInterval=setInterval(countDown,1000);
var control:Timer = new Timer(1000,0)
control.addEventListener(TimerEvent.TIMER, keko)
control.start();
 
function keko (evt:Event):void{

if(dispMins <1 && dispSecs <1 )
{
timeisup.visible = true;
timeisup.play();
}
}
 
function countDown()
{
dispSecs--;
if (dispMins == 0 && dispSecs == 0)
{
clearInterval(timerInterval);
}
else if (dispSecs == 0)
{
dispSecs = 59;
if (dispMins > 0)
{
dispMins--;
}
}
time.text = prependZero(dispMins) + ":" + prependZero(dispSecs);
}  
 
function prependZero(num)
{
if(num<10)
{
num=""+num;
}
return(num);
} 

The last code I tried.But it's not work exactly.

pause1.addEventListener(MouseEvent.CLICK, pauseGame);
function pauseGame(event:MouseEvent):void{
 stage.frameRate = 0;
}
play1.addEventListener(MouseEvent.CLICK, resumeGame);
function resumeGame(event:MouseEvent):void{
stage.frameRate = 15;
}

Using AS3 to play symbol on hover and then play movie clip on clip?

I have an animation playing in the background (entire animation nested in a symbol). I have a button (name "circlebutton" in another layer). I want that button to play an animation ( "circlehover" simple pulsating color for the button) on hover and then play a separate animation (a white box covering the entire screen) on button click.

I am not even going to post the code I have because it isn't working. I appreciate any help/tips and especially appreciate detailed instruction. A lot of the tutorials I've already looked at tell me what code to paste but not where to paste it (i.e. should I paste it in a separate layer called actions or should I paste it in the first frame of the symbol layer?)

Thanks so much

as3 - Error: Classes must not be nested

I tried to generate a preloader class linked in the main class in as3 but now my main class keeps getting an error on compile.

I don't know why this is happening because the code was working earlier. If it helps my ide is flashdevelop 5.2.0.3

Before when I try to compile I initially get "Error: null", Build halted with errors (fcsh). and then on attempting to compile again I get "Error: Classes must not be nested."

Any help would be greatly appreciated.

(skipping import statements and package)

    [Frame(factoryClass="Preloader")]

    public class Main extends Sprite {

      private var adventure_model:AdventureModel;

      private var title_view:TitleView;
      private var title_controller:TitleController;

      protected var panelCollection:PanelCollection = null;


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

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

        panelCollection = new PanelCollection();
        adventure_model = new AdventureModel();
        title_controller = new TitleController(adventure_model, panelCollection);
        title_view = new TitleView(adventure_model, title_controller, "title_view", 0, 0, panelCollection);
        addChild(title_view);
    }

}

AS3/AIR Load/Save Username progress

I am creating an Android application created using Flash AS3. The user will input his/her name, click the previous and next button and press save. After restarting the application, the last frame saved was loaded (with the name). However if I want to input 2nd user with different name and save it in different frame, will the 2nd user's save progress be retained (without deleting the progress of the 1st user?). The problem, when I type the previous user name progress and press load, his saved progress doesn't load. Please help.

I am a newbie in programming. Here is my code so far:

*import flash.events.MouseEvent;


var savedstuff:SharedObject = SharedObject.getLocal("myStuff");

btnSave.addEventListener(MouseEvent.CLICK, SaveData);
btnLoad.addEventListener(MouseEvent.CLICK, LoadData);
btnNext.addEventListener(MouseEvent.CLICK, pageNext);
btnPrev.addEventListener(MouseEvent.CLICK, pagePrev);


function pageNext (e:MouseEvent){
    nextFrame();
}

function pagePrev (e:MouseEvent){
    prevFrame();
}

function SaveData(MouseEvent){
 savedstuff.data.username = nameField.text 
 savedstuff.flush();
 }
function LoadData(MouseEvent){
 if(savedstuff.size>0){ 
 nameField.text = savedstuff.data.username} 
 gotoAndStop(savedstuff.data.saveData);
 }


if(savedstuff.size>0){
nameField.text = savedstuff.data.username}* 

Actionscript 3.0. How to calibrate collision detection?

This is for a flash game that I am working on. I am trying to improve the collision detection between LevelOnePlayer and Wall11. However, even if I change the Wall Hit Detection variables by 0.1 pixels, the game keeps on detecting collision when the player is too close or too far from the walls. Is there anyway to make the collision detection pixel perfect?

const LEFT_WALL_HIT_DETECTION: Number=5.5;
const RIGHT_WALL_HIT_DETECTION: Number=5.5;
const UP_WALL_HIT_DETECTION: Number=5.5;
const DOWN_WALL_HIT_DETECTION: Number=5.5;
const ENEMY_HIT_DETECTION: Number=5.5;

var left:Boolean = false;
var right:Boolean = false;
var up:Boolean = false;
var down:Boolean = false;

var leftBumping:Boolean = false;
var rightBumping:Boolean = false;
var upBumping:Boolean = false;
var downBumping:Boolean = false;



var Onespeed: Number=3.5;
var LevelOneStartFrame: Number=1010; 
addEventListener(Event.ENTER_FRAME, LevelOne);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased); 
    function keyPressed(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            left=true; 
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            right=true;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            up=true;  
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            down=true; 
        }
    }
    function keyReleased(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            left=false;
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            right=false;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            up=false;
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            down=false;
        }
    }
    function LevelOne(event:Event){
        if(left){
            LevelOnePlayer.x-=Onespeed; 
        }
        if(right){
            LevelOnePlayer.x+=Onespeed; 
        }
        if(up){
            LevelOnePlayer.y-=Onespeed; 
        }
        if(down){
            LevelOnePlayer.y+=Onespeed; 
        }
        if(Wall11.hitTestPoint(LevelOnePlayer.x-LEFT_WALL_HIT_DETECTION,       LevelOnePlayer.y, true))
        leftBumping=true; else leftBumping=false;
        if(Wall11.hitTestPoint(LevelOnePlayer.x+RIGHT_WALL_HIT_DETECTION, LevelOnePlayer.y, true))
        rightBumping=true; else rightBumping=false;
        if(Wall11.hitTestPoint(LevelOnePlayer.x, LevelOnePlayer.y+DOWN_WALL_HIT_DETECTION, true))
        downBumping=true; else downBumping=false;
        if(Wall11.hitTestPoint(LevelOnePlayer.x, LevelOnePlayer.y-UP_WALL_HIT_DETECTION, true))
        upBumping=true; else upBumping=false;

        if(leftBumping) LevelOnePlayer.x+=Onespeed;
        if(rightBumping) LevelOnePlayer.x-=Onespeed;
        if(downBumping) LevelOnePlayer.y-=Onespeed;
        if(upBumping) LevelOnePlayer.y+=Onespeed;
    }

I have performance issues with the code I'm using to detect collision between items

I managed to make this work and do what I needed after a while but now my problem is performance. As you can see I need it for 14+ items. I tested at first for 5 items and it worked ok but after I added more the performance dropped a lot. As for the collision detection class, I assume you know what it does and how it works(that I managed to make it work since the registration point only works when set to upper left side of the movie clip and mine was in the middle) If you need any other details or information please don't hesitate to ask and I will try my best to provide it. So in a few words what is need is: -

  • I have 14+ objects and need to display them
  • I need a unique random position for every object
  • Make new random position and check to see if it's shape collides with the other objects
  • If that object doesn't collide with the other object displayed the movieClip
  • If that object collides with another movieClip get another random position
  • Check again the object with the other objects to see if it collides
  • If YES find another position / If NO show the object
  • Do this until all the objects are positioned without colliding with each other

I believe I'm missing something and that this code could be better but really don't have any other good ideas and didn't find anything on the internet that might help. Please give me a hand.

*** Also keep in mind that I don't want the grid solution for collision detection


private var objArray : Array = new Array (movieClip1, movieClip2, movieClip3, movieClip4, movieClip5, movieClip6, movieClip7, movieClip8, movieClip9, movieClip10, movieClip11, movieClip12, movieClip13, movieClip14);
private function init():void
    {
        trace("[TRACE]:Init GameScreen");
        addEvents();
        startTimerCollision();
    }
private function addEvents():void
    {
        _timer.addEventListener(TimerEvent.TIMER, timer); //Listen for the Timer event _timer and trigger the function timeLeft.
        Repository.STAGE_REF.addEventListener(Event.ENTER_FRAME, frameRate);
    }
private function startTimerCollision():void
    {           
        _timer.start();                         //start the timer

        _collisionCheck = new CollisionTest();
    }
private function frameRate(event:Event):void
    {
        //add 1 to the frame count every frame
        _frame++;
    }
function timer(event:TimerEvent):void
    {   
        timpul--
        _TimerSound.play();

        showObjs();
    }
private function randomPosition(obj:MovieClip):void
    {
        obj.x = obj.width + Math.random() * (stage.stageWidth - obj.width * 2);
        obj.y = obj.height + Math.random() * (stage.stageHeight - obj.height * 2);  
    //  trace(obj + " RANDOM POS= " + "x: " + obj.x + " / y:" + obj.y);
    } 

    private function randomALLPositions():void
    {
        for (var i = 0; i < objArray.length; i++)
        {
            randomPosition(objArray[i]);
        }
    }

    private function checkAllCollision(obj:MovieClip):Boolean
    {
        var collisionStatus : Boolean;
        for (var i = 0; i < objArray.length; i++)
        {
            if (obj != objArray[i])
            {               
                if (_collisionCheck.complex(obj, objArray[i]))
                {
                    collisionStatus = true;
//                  trace("collision detected: " + obj + " and " + objArray[i]);
                    randomPosition(obj);
                    checkAllCollision(obj);
                }
                else
                {
                    collisionStatus = false;
                }
            }
        }
        return collisionStatus;
    }

    private function showObjs():void
    {

        ////////////////////////////////////////////////////////ONLINE
        var i:int = 0;
        var j:int;
        var l:int = objArray.length;

        for (i; i < l; i++)
        {
            randomPosition(objArray[i]); 
            for (j = 0; j < l; j++)
            {
                if (objArray[i] != objArray[j])
                {
    //              trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> CHECKING");
                    //while (checkAllCollision(objArray[i]))
                    if(checkAllCollision(objArray[i]) == true)
                    {
    //                  trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> Collision DETECTED");
                        randomPosition(objArray[i]);
    //                  trace("OBJ "+ (i+1) + " NOW= " + "x: " + objArray[i].x + " / y:" + objArray[i].y);
                    }
    //              trace("OBJ " + (i+1) + " with OBJ " + (j+1) + "---------> OK");
                }
            }
            addChild(objArray[i]);

        }
        ////////////////////////////////////////////////////////ONLINE

        for (var z = 0; z < objArray.length; z++)
        {
            TweenLite.to(objArray[z]["gime" + (z+1)], /*time:*/ 0, {scaleX:0, scaleY: 0});
            TweenLite.to(objArray[z]["gime" + (z+1)], /*time:*/ 0.5, {scaleX:1, scaleY: 1});
        }   
    }

Is there any modern way to do games with ActionScript?

I know it is possible to develop games with ActionScript. My question is:

Is there any way to generate a game like "Unity" does, with Adobe tools, without ask the user to install 3rd party plugins (Flash Player, Adobe Air)?

I would like to do a game with ActionScript, for mobile platforms, without the inconvenience of installing third party plugins. Is it possible?

How are made games like Clash Royale?

Appreciate.

as3 How to dispatch a specific keyboard event

I was looking for this answer and had no luck. One place I looked actually had a very discouraging answer: "You cannot force mouse or keyboard events - they HAVE TO come from mouse or keyboard."

Huh?

I tried 'brute force' and came up with this solution. Maybe I'm going about it wrongly or stupidly; is there a better way?

I had a keyboard event that launched a class and wanted to put a sprite on the stage that would initiate this same action -- clicking on the sprite would launch the keyboard event (Escape key).

In the eventListener function, I traced the event e itself:

    private function keys(e:KeyboardEvent):void {
        trace("EscapeKey: ",e);   
        if (e.keyCode == 27) {
        ...    
        }
    }

The output was

EscapeKey: [KeyboardEvent type="keyDown" bubbles=true cancelable=false eventPhase=2 charCode=27 keyCode=27 keyLocation=0 ctrlKey=false altKey=false shiftKey=false]    

I then had the mouseClick listener create and dispatch a new keyboardEvent using the values I got from the above trace:

    private function pauseClick(e:MouseEvent):void {
        var a:KeyboardEvent = new KeyboardEvent("keyDown", true, false, 27, 27, 0, false, false, false);
        stage.dispatchEvent(a);
    }

Presto!
Hopefully, this post will come in handy to others looking for these types of mouse/keyboard event redundancies.

actionscript3 how to manage memory in ios

So we have developed an app using AIR that runs smoothly on android but crashing on iOS. The app just has a preloader and a folder containing a bunch of precompiled SWF files. The user loads one of the SWF called labs files and runs it. It looks something like this:

preloader

Now, everything worked fine and all, but once a person loads a lab, the new lab has multiple frames and in the beginning the app runs smoothly but as the user keeps loading frames the app crashes without any errors. I used the debugger in Adobe Flash Professional CC 2016 and there was no error, checked logs etc. still no luck. In the end I just used Instruments and looked up the memory usage. Apparently as frames loaded the application used up all the memory and in the end crashed. The Activity Monitor looked really nasty :

activity monitor

now my question is, is there a specific method to manage memory in actionscript3 from adobe's side?

Use a child in as3 adobe animate

I making a card game and i call some cards from the library randomly. But i cant use this cards. Is there any way to make this childs clickable? And another question please. If there any chance to use one print array for all the 22 cards i need to show on stage?Or i must to create a new printarray and a new random number for each card? Note:each card has different points.

var cards:Array = [k1, p1, s1, r1, r3,k4,p4,s4,r4,k5,p5,s5,r5
 ,k6,p6,s6,r6,k7,p7,s7,r7,k8,p8,s8,r8,k9,p9,s9,r9,k10,p10,s10,r10,
 kj,pj,sj,rj,kq,pq,sq,rq,kk,pk,sk,rk];

var printArray:Array = [];

for (var n:int = 1; n <= 1; n++)
{
    var randNo:int = int(Math.random() * 51);
    printArray.push(randNo);
}

for (var c:int = 0; c < printArray.length; c++)
{
    trace(printArray[c]);
    var mc:MovieClip = new cards[printArray[c]  ];
    addChild(mc);
    mc.width = 60;
    mc.height = 80;
    mc.x = 100;
    mc.y = 50;
}


var print1Array:Array = [];

for (var n1:int = 1; n1 <= 1; n1++)
{
   var rand1No:int = int(Math.random() * 51);
   print1Array.push(rand1No);
}

for (var c1:int = 0; c1 < print1Array.length; c1++)
{
    trace(print1Array[c1]);
    var mc1:MovieClip = new cards[print1Array[c1]  ];
    addChild(mc1);
    mc1.width = 60;
    mc1.height = 80;
    mc1.x = 70;
    mc1.y = 80;
}

stage.addEventListener(Event.ENTER_FRAME,looping);
function looping(event:Event):void
{
    //here ia want use the cards.Let say i want to if(mc1 is clicked)
}

mardi 24 janvier 2017

flex - make text book with textArea

There are two TextAreas of spark components horizontally.

left TextArea id : taLeft

right TextArea id : taRight

and there is very long String.

var str:String = "blarblar....";

first, taLeft.text = str;

I input str to taLeft.

just then, I want input the rest string of taLeft viewport's height outside to taRight.

How can I do this work fast?

I tried something getting the last line string of taLeft with taLeft's textFlow, but the way was very slow...'cause all string is very loooong..

is there good idea? can I get more tip?

help me please and thank you.

How do I get the node in an XML document when given a row and column or an index in AS3?

I have a text area that is populated with the contents of an XML document. I'm trying to get the node that the user has placed his cursor in.

I can easily get the row and column or the index of the cursor. I can also create an XML object via new XML(textarea.text).

What would be great is if there is a XML.getNodeAtPosition(index) or XML.getNodeAtPosition(row, column) method.

Here is example code:

var row:int = 100;
var column:int = 10;
var xmlText:String = fileLoader.data as String;
textarea.text = xmlText;
textarea.setAnchor(row, column); // simulate user cursor
var xml:XML = new XML(textarea.text);
var node:XML = xml.getNodeAt(row, column);

Note:
The XML may be edited by the user and may not be valid XML. I don't think Flash will create an XML object unless it is completely valid but it would be great if it was possible.

How much wood will this woodchuck chuck?

Does this code make sense? I did not write it but was given it as a question I need some help as to what the answer is if there even is one, thanks in advance.

for (var i : int = 0;  i <10; i++)
{
woodchuck.chuck(wood);
if(i%2)
{i++;}
}

Odd 1084: Syntax error: expecting rightbrace before end of program

I need a help. It is about rightbrace. Seems there is a problem. I don't know where is the mistake as previous code does not have a problem, but then latter there is a problem. With 1084: Syntax error: expecting rightbrace before end of program.

if (counterEnergy == 1){
                energyFlame1.gotoAndStop(1)
                energyFlame2.gotoAndStop(2)
                energyFlame3.gotoAndStop(2)
                energyFlame4.gotoAndStop(2)
                energyFlame5.gotoAndStop(2)
            }
            else if (counterEnergy == 2){
                energyFlame1.gotoAndStop(1)
                energyFlame2.gotoAndStop(1)
                energyFlame3.gotoAndStop(2)
                energyFlame4.gotoAndStop(2)
                energyFlame5.gotoAndStop(2)
            }
            else if (counterEnergy == 3){
                energyFlame1.gotoAndStop(1)
                energyFlame2.gotoAndStop(1)
                energyFlame3.gotoAndStop(1)
                energyFlame4.gotoAndStop(2)
                energyFlame5.gotoAndStop(2)
            }
            else if (counterEnergy == 4){
                energyFlame1.gotoAndStop(1)
                energyFlame2.gotoAndStop(1)
                energyFlame3.gotoAndStop(1)
                energyFlame4.gotoAndStop(1)
                energyFlame5.gotoAndStop(2)
            }
            else if (counterEnergy == 5){
                energyFlame1.gotoAndStop(1)
                energyFlame2.gotoAndStop(1)
                energyFlame3.gotoAndStop(1)
                energyFlame4.gotoAndStop(1)
                energyFlame5.gotoAndStop(1)
            }
            else if (counterEnergy == 0){
                energyFlame1.gotoAndStop(2)
                energyFlame2.gotoAndStop(2)
                energyFlame3.gotoAndStop(2)
                energyFlame4.gotoAndStop(2)
                energyFlame5.gotoAndStop(2)
            }

How do I get an animation to play in full using the "down" part of a button?

I have the up and over functions (if that is the term?) working but I want to make the green bar expand across the screen for the down function (so when then click on the blue go button I want the green bar to expand fully across the screen). Currently, if I click on the blue button the green button plays for only as long as it's clicked. I would like to click once and have it play in full. Tia

Example

Flash AS3 enable/disable buttons from inside movie clip (MC is linked to scrollpane)

I have scene1 within that scene1, i have "Next" button and i have scroll pane which is linked to MC1 with bunch of form fields. so i am trying to enable / disable buttons from the MC1. since the buttons on scene1 stage, am trying to validate my form fields then enable button. but when i test it, says undefied property.. here is the code which is included in MC1 inside.

// Step 4 Validation start here (these buttons on scene1 stage)

bttnNext4.visible = false; bttnNext4_disabled.enabled = false; 


//Next button
bttnNext4.addEventListener(MouseEvent.CLICK, step4tostep5);

function step4tostep5(event: MouseEvent): void {
    if (validateForm3()) {
        gotoAndStop(20);
    }
}
// Validation
function validateForm3(): Boolean {
    return name_step4.text != "" && validate_step4();
}

//event
name_step4.addEventListener(Event.CHANGE, ChangeEvent3);
combosmall_step4.addEventListener(Event.CHANGE, ChangeEvent3);
combosmall2_step4.addEventListener(Event.CHANGE, ChangeEvent3);
combosmall3_step4.addEventListener(Event.CHANGE, ChangeEvent3);
txtsmall_step4.addEventListener(Event.CHANGE, ChangeEvent3);
txtsmall2_step4.addEventListener(Event.CHANGE, ChangeEvent3);
txtsmall3_step4.addEventListener(Event.CHANGE, ChangeEvent3);

function ChangeEvent3(event: Event): void {

    var enabled = name_step4.text != "" &&  validate_step4();
    bttnNext4.visible = enabled; 
     bttnNext4_disabled.visible = !enabled;
}
function validate_step4(){
    var enabled = false;
    if(combosmall_step4.selectedIndex > 0 || combosmall2_step4.selectedIndex > 0 || combosmall3_step4.selectedIndex > 0)
        enabled = true;
    if(combosmall_step4.selectedIndex == 0 ){
        enabled = txtsmall_step4.text != "";
    }
    if(combosmall2_step4.selectedIndex == 0){
        enabled = enabled && txtsmall2_step4.text != "";
    }
    if(combosmall3_step4.selectedIndex == 0){
        enabled = enabled && txtsmall3_step4.text != "";
    }
    return enabled;
}



//combo box selection

combosmall_step4.addEventListener("change", ComboChangeEvent5);
combosmall_step4.dispatchEvent(new Event("change", true));
function ComboChangeEvent5(event: Event): void {
    if (combosmall_step4.selectedIndex == 1 ||  combosmall_step4.selectedIndex ==2  ) {
         txtsmall_step4.visible=false;

    }
    else
    {
        txtsmall_step4.visible=true;

    }
}

combosmall2_step4.addEventListener("change", ComboChangeEvent5A);
combosmall2_step4.dispatchEvent(new Event("change", true));
function ComboChangeEvent5A(event: Event): void {
    if (combosmall2_step4.selectedIndex == 1 ||  combosmall2_step4.selectedIndex ==2  ) {
         txtsmall2_step4.visible=false;
        GB1_step4.visible = false;
    }
    else
    {
        txtsmall2_step4.visible=true;
        GB1_step4.visible = true;
    }
}

combosmall3_step4.addEventListener("change", ComboChangeEvent5B);
combosmall3_step4.dispatchEvent(new Event("change", true));
function ComboChangeEvent5B(event: Event): void {
    if (combosmall3_step4.selectedIndex == 1 ||  combosmall3_step4.selectedIndex ==2  ) {
         txtsmall3_step4.visible=false;
        GB2_step4.visible = false;
    }
    else
    {
        txtsmall3_step4.visible=true;
        GB2_step4.visible = true;
    }
}

ActionScripts3 POST to URL issue

I'm trying to use API of SMSPVA.com, when i copy and paste URL to Firefox it return json values, but in Actionscripts3 wrong value appear in output. I thing my code is not right.

I want to POST data over URL and print response with "trace" in output window.

import flash.net.*;

function URLRequest_method() 
{
    var url:String = "http://ift.tt/2jMAY6R";
    var request:URLRequest = new URLRequest(url);
    var variables:URLVariables = new URLVariables();
    request.method = URLRequestMethod.POST;

    trace(request);
}
URLRequest_method();

lundi 23 janvier 2017

AS3/AIR Save/Load multiple usernames using SharedObject

I am trying to create an Android application created using Adobe Flash Actionscript 3. I wanted each user of the app to input their name in the beginning of the application, then they have the capability to save their progress in current frame (and it will be saved into a save slot or similar). However, the problem arises when another user is going to use the app, he/she must enter a distinct username, and he/she can save anytime (and load his/her distinct load progress, different from the previous user.). And it goes on.

I am a newbie in programming and I hope you could help me. Any suggestions will be appreciated. Thanks!

This my code for creating a username and saving it:

function handleClick(Event:MouseEvent):void
{
    var myFirstVariable = boxOne.text;
    boxTwo.text = myFirstVariable;
    gotoAndStop("opening_scene")
}
myButton2.addEventListener(MouseEvent.MOUSE_UP, handleClick);

Here is my code for saving and loading:

var mySharedObject:SharedObject = SharedObject.getLocal("save");

btnSave.addEventListener(MouseEvent.CLICK, saveCurrentFrame);
btnLoad.addEventListener(MouseEvent.CLICK, getLastFrame);

function saveCurrentFrame(event:MouseEvent):void
{
    mySharedObject.data.lastframe = currentFrame;
    mySharedObject.flush();
}

function getLastFrame(event:MouseEvent):void
{
    if (mySharedObject.data.lastframe != null)
    {
        gotoAndStop(mySharedObject.data.lastframe);
    }
} 

How to play animation and then play reverse on hover, start playing again until end on hover out using in Adobe Animate (Flash)?

Sorry this is so specific but I have combed through so many pages and videos and tutorials and can't figure this out.

I have all of my animations within a MovieClip. In the movie clip is also a stage sized white square button with the instance name "btn". Back on the main stage I have a second layer called "actions" with the following code applied to the first (and only) frame. It's not working. At all. (HUGE) tia

stop();  // this will stop the movie from playing at the start

btn.addEventListener((MouseEvent.ROLL_OVER, playMovie);
btn.addEventListener((MouseEvent.ROLL_OUT, stopMovie);

function playMovie(evt:MouseEvent):void {
 play();
}

function stopMovie(evt:MouseEvent):void {
 stop();
}

Mx Tree fails when duplicate items are added to an existing node

I'm maintaining a large legacy Flex 4.6 project which refuses to die and have run into an issue with the Mx Tree component that I have not been able to solve. The gist is that adding items to an existing node exhibits weird behavior if the items are duplicates. If the node is created with duplicate items the component behaves as expected.

For example, the image below shows the result of adding the file "AAAAA.png" multiple times to the existing node. The highlighting goes berserk and the component seems to get confused about how many items it has (have tested this).

I've tried the "refresh tree" hack (below) of resetting the data provider, etc. and I call refresh on the various backing Array Collections. I started to go down the road of replacing the Mx Tree with a Spark Tree that someone came up with but it was turning into too much time.

Before I tell the client to let go of this feature, does anyone have a thought about what the issue might be? I am more of an Actionscript than a Flex developer and don't know my way around components beyond just using them.

enter image description here


    protected function vfAddToBtn_clickHandler(event:MouseEvent):void
    {
        if (virtualFoldersList.selectedItem == null){
            Alert.show("Please select a virtual folder to add to", "Add to Virtual Folder", Alert.OK);

        } else {
            if (briefcaseData.currentSelectionsList.length > 0){
                var vf:VirtualFolder = virtualFoldersList.selectedItem as VirtualFolder;

                if (vf != null){
                    vf.children.addAll(briefcaseData.currentSelectionsList);
                    vf.children.refresh();
                    briefcaseData.virtualFoldersArray.refresh();
                    refreshTree(virtualFoldersList);

                } else {
                    trace("ERROR: vfAddToBtn_clickHandler vf is null");
                }
            }
        }
    }


        private function refreshTree(tree:Tree) : void
        {
            var selectedIndex : int = tree.selectedIndex;
            var openItems : Object = tree.openItems;
            tree.dataProvider = tree.dataProvider;
            tree.openItems = openItems;
            tree.validateNow();
            tree.selectedIndex = selectedIndex;
        } 

AS3 Converting MouseEvent to KeyboardEvent

i'm working on a DDR game for my Game Programming course and I was able to get the arrows to work using the mouse. But a requirement is to also get it to work using the keyboard too. I can't exactly get it to work using the keyboard.

Here is my source code, how would I convert the MouseEvent's to work using KeyboardEvents for the up, bottom, left and right buttons?

import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flashx.textLayout.operations.ModifyInlineGraphicOperation;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundChannel;

var pattern = new Array();
var buttons = new Array();
buttons.push(up, bottom, left, right);
var position = 0;
var playersTurn = false;
var mc_starttext:MovieClip;
var mc_background:MovieClip;

//generate the pattern
setTimeout(nextMove, 1000); // call after 1 second

// Expecting click from they keyboard

up.addEventListener(MouseEvent.CLICK, clicked);
bottom.addEventListener(MouseEvent.CLICK, clicked);
left.addEventListener(MouseEvent.CLICK, clicked);
right.addEventListener(MouseEvent.CLICK, clicked);

stage.addEventListener(KeyboardEvent.KEY_DOWN, onkeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP, onkeyRelease);


mc_starttext.buttonMode = true;
mc_starttext.addEventListener(MouseEvent.CLICK, startClick)
mc_background.buttonMode = true;
mc_background.addEventListener(MouseEvent.CLICK, startClick)


function startClick(e:MouseEvent):void{
            dispatchEvent(new Event("START_GAME"));
        }

function hideScreen():void{
            this.visible = false;
        }

function showScreen():void{
            this.visible = true;
        }

function onkeyPress(event:KeyboardEvent):void{

    if (event.keyCode == 13)//enter
                {
                    this.mc_background.visible = false
                    this.mc_starttext.visible = false
                    //this.StartCover.visible = false; 
                    //this.StartText.visible = false;

                    //this.score.text = position.toString();
                    //this.score.visible = true;

                    //startPlay = true;
                    setTimeout(nextMove, 2000);//Call nextmove after two second

                }

    if (event.keyCode == 32)
    {
        trace("space bar");
    }
}

function onkeyRelease(event:KeyboardEvent):void{
    if (event.keyCode == 32){
        trace("space release");
    }
}

function clicked(clickInfo:MouseEvent){

    if(!playersTurn) return;

    if (clickInfo.target == pattern[position]){
        trace("right");
        position = position + 1;
        //Check to see if it is computers turn
        if (position == pattern.length){
            //CPUs turn
            position = 0;
            setTimeout(nextMove, 1000)
        }
        // play button animation
        clickInfo.target.gotoAndPlay(2);
    } else {
        trace("wrong");
    }

}

function nextMove(){

    if (position < pattern.length){
        pattern[position].play();
        position++;
        setTimeout(nextMove, 1000);
    } else {
        // Generate random number
        var randomNumber = Math.floor(Math.random()*4);
        pattern.push(buttons[randomNumber]);
        buttons[randomNumber].play();
        playersTurn = true;
        position = 0;
    }
}

Animate / EaselJS - removeEventListener not working

I have an issue w/ Adobe Animate CC, and the Javascript framework it uses, EaselJS/CreateJS. I can add event listeners w/o issue, but I cannot remove them. I have tried various things from the debugger, including stepping into their JS removeEventListener handler - Although the two variables look identical, they are never == (or ===) so the even listener isn't removed.

Here is the code I use, and it's purpose it to fade-in an element when hovering over it:

this.fadeIn = function(target_mc)
    {
        target_mc.alpha = 0;
        target_mc.visible = true;

        target_mc.removeEventListener("tick",fadeIn_onEnterFrame);
        target_mc.addEventListener("tick",fadeIn_onEnterFrame.bind(this));

        function fadeIn_onEnterFrame(evt)
        {
            evt.currentTarget.alpha = evt.currentTarget.alpha + .2;
            if (evt.currentTarget.alpha >= 1)
            {
                evt.currentTarget.removeEventListener("tick",fadeIn_onEnterFrame);
            } // end if
        }
    } // End of the function

So you know, it is added to the Canvas in frame_0, and is called from a "mouseover" listener added to each clothing type (it's for a drag-and-drop dress-up game, FWIW)

function clothing_onRollOver()
{
    this.hint_mc.desc_mc.desc1_txt.text = this.articleName;
    this.fadeIn(this.hint_mc);
    this.clothingOver = true;
};
clothing.addEventListener("mouseover",clothing_onRollOver.bind(this));

ActionScript 3.0 Load PDF

I am trying to load a PDF into my Adobe Air Application using ActionScript, On my machine I have the latest Adobe Acrobat Reader DC and Adobe Acrobat XI Pro.

I have been following these steps on this tutorial: http://ift.tt/2jTZB4n

but I am stuck here:

if(HTMLLoader.pdfCapability == HTMLPDFCapability.STATUS_OK)  
{ 
    trace("PDF content can be displayed"); 
} 
else  
{ 
    trace("PDF cannot be displayed. Error code:", HTMLLoader.pdfCapability); 
}

but it keeps saying PDF cannot be displayed. Error code: 3204 which is An error was returned by the OS when trying to load the Adobe Reader or Acrobat application or one of its necessary libraries.

Am I missing something here? Or don't have something installed properly?

dimanche 22 janvier 2017

Log in through facebook app if the user has the facebook app installed?

I am working with the latest versions of Starling and FeathersUI using Flash Builder 4.7

Currently I have added a "log in/sign up through facebook" option into my mobile application. The option works by using the Feathers WebView component to open the url:

http://ift.tt/2iTqwNX

I then wait for the starling.events.Event.COMPLETE event which tells me the page has finished loading - I can then access the location of the WebView (browser) to get the access token to validate their log in.

My question is: If a user has the Facebook App installed already on their phone, how can I make my app automatically check the Facebook App for the users login, rather than sending to the web-browser log in page for facebook?

I am aware of ANEs that provide functionality for this, but is there a way without using an ANE? Perhaps there is a facebook log in page that gives the option of connecting through facebook app? This ANE (http://ift.tt/1fIJAVg) seems to have that option, but am unsure where to direct the user to within my app in the WebView to have that "log in through facebook app" option appear?

I will later want to include things like Posting to users walls (if they choose to), sharing links etc. so perhaps I need to use a social plugin ANE (I dont think those work for desktop versions of the app though unfortunately).

flex,as3 android - Is there any library for viewer of E-pub files?

I'm developing the viewer of E-pub files in environment of flex mobile.

(flash builder 4.7)

but it is so hard work with publishing of html files.

so I wonder that some library of E-pub viewer exists for flex android.

can I get some information of this?

ActionScript 3.0 sound not working

So having trouble making sound on keyboard press

I have the imports:

import flash.net.URLRequest;
import flash.media.Sound;

I have the variables

private var soundDownRequest:URLRequest = new URLRequest ("SoundDown.mp3");
private var downSound:Sound = new Sound (soundDownRequest);

and the event listener

private function keyDownHandler(evt:KeyboardEvent):void
    {

            if (evt.keyCode == 40)//ascii for down arrow 
            {
                downSound.play();

            }
    }

The sound folder is in the same folder as the .as, its also in the library of the fla, yet it still doesn't work. Any idea why?

Thank you.

Actionscript 3 - One event listener with multiple occurances

I have a sound effect that is being triggered every time an object gets hit in my game. This effect could be triggered one time, 10 times, 30 times, or anywhere in between. This all works just fine and was never a problem... until I decided that I wanted the sounds to finish playing before the next round could begin. So I put in an addEventListener every time the sound was called on to play and added a boolean flag saying it was playing. Once it was done I removed the listener and changed the boolean flag back to false. Something like this:

internal function boomSound():void {
    _sfxChannel = _goBoom.play(25);
    _boomPlaying=true;
    _sfxChannel.addEventListener(Event.SOUND_COMPLETE, boomSoundFinished, false, 0, true);
}

internal function boomSoundFinished(event:Event):void {
    _sfxChannel.removeEventListener(Event.SOUND_COMPLETE, boomSoundFinished);
    _boomPlaying=false;
}

However, this lead to a problem because I didn't have unique events happening. So when the first boom finished, the eventListener would fire and remove itself. But if a second boom had started before the first was done, it was again adding the same eventListener which was getting removed by the first boom finishing. So now the 2nd boom didn't have an event listening for it anymore. And then maybe a third, forth, fifth would occur and maybe get a complete event, or maybe not. This lead to _boomPlaying=false even if there was still a boom playing.

So is there a way to make this work? I was thinking of something along the lines of an array to store the events and giving them a different number each time it's triggered, and then removing them in the remove function... but that seems like a pretty complicated solution. I was reading about event.currentTarget but when I try to trace that I'm just getting the reference to the SoundChannel and event.currentTarget.name gives an error because I haven't set a name up. Can anyone point me in the right direction here please? Thanks in advance!

Im trying to import a game class and i get this message when i startup "Cannot access a property or method of a null object reference."?

I'm making an app for an assignment and i'm importing this game onto a page for some to click on a button at the game pops up. But i get this error and i've searched online and people say it could be anything..... I'm a beginner at AS3 so i'm not good at coding, but does anyone know why this is happening?

I would like the bottle to be in a random order but I'll have to come to that when it appears for me.

Here's the code:

package {

import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;

public class Shoot extends MovieClip {

    private var bottleArray:Array = new Array();
    private var numOfBottle:uint = 9;
    private var bottleHit:uint = 0;
    private var hits:uint = 6;
    private var bg:Sprite;

    var bottle:MovieClip = new Bottle
    var shots:MovieClip = new Shots
    var endBox:MovieClip = new EndBox

    public function Shoot() {

    addEventListener(Event.ENTER_FRAME, enterHandler);


       //Adds the bottles onto the stage.
       for (var i:int = 0; i < numOfBottle; i++) {
        bottle.x = 0 + (i * 200);
        bottle.y = 344.35;
        bottle.addEventListener(MouseEvent.CLICK, clickHandler);
        addChild(bottle);
        bottleArray.push(bottle);
       }

       //Adds a invisibe background to detect when the targets have been missed.
       bg = new Sprite();
       bg.graphics.beginFill(0x000000,0);
       bg.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
       bg.graphics.endFill();
       addChildAt(bg,0);
       bg.addEventListener(MouseEvent.CLICK, checkShots);

       //Adds the number shot left to stage. 
       shots.x = 480;
       shots.y = 80;
       addChild(shots);

       addChild(endBox);
       endBox.x = 220;
       endBox.y = 550;
       endBox.visible = false;

      }


      //This function moves all the bottles in the array four pixels to the 
      //right at the current frame rate. If a bottle goes passed the stage 
      //width, it will get re-added a bottle width before the start of the stage.
    function enterHandler(e:Event):void{
       for (var j:uint = 0; j <  bottleArray.length; j++) {
        bottleArray[j].x +=  1;

        if (bottleArray[j].x > stage.stageWidth + bottleArray[j].width) {
         bottleArray[j].x = 0 - bottleArray[j].width;
        }
       }
      }


      //This removes the bottle from the stage, the event listener and 
      //removes it from the array if it has been clicked. 
      function clickHandler(e:MouseEvent):void {
       var index:uint = bottleArray.indexOf(e.currentTarget);
       var target:MovieClip = e.currentTarget as MovieClip;

       target.removeEventListener(MouseEvent.CLICK, clickHandler);
       removeChild(target);
       bottleArray.splice(index, 1);

       checkShots();
      }


      function checkShots(e:MouseEvent = null):void{
       //This increments the bottleHit counter by one and goes to 
       //the next frame in shots movie clip.
       bottleHit++;
       shots.gotoAndStop(shots.currentFrame + 1);


       //If there are no more shot available and array length is six then you win. 
       if (shots.currentFrame == shots.totalFrames && bottleArray.length == hits) {
        removeObject();
        endBox.visible = true;
        endBox.gotoAndStop(1);
       }
       //If there are no more shot available you lose.
       else if (shots.currentFrame == shots.totalFrames) {
        removeObject();
        endBox.visible = true;
        endBox.gotoAndStop(2);
       }
      }

      //This removes the event listeners
      function removeObject():void{
       removeEventListener(Event.ENTER_FRAME, enterHandler);
       bg.removeEventListener(MouseEvent.CLICK, checkShots);

       for (var i:int = 0; i < bottleArray.length; i++){
        bottleArray[i].removeEventListener(MouseEvent.CLICK, clickHandler);
       }
      }
     }
    }

check if swf file is being played on our own server

I'm creating games creating flash cc(as3). I just create game files and give it to other department and they upload it. I don't have any knowledge on php. My problem is if the file is uploaded to the website, it can be downloaded. My question is if it is possible to restrict it from downloading the file. If not, then restrict the file from being played on their own. I've came across a file which can be played on their server but if I download it and try to run on my desktop, it won't play. How to achieve something like that? I try to connect to server from the swf file before it can be played. If the file get proper key then only the file will play. But to do so I need user permission. Can it be done without user permission? Any help would be appreciated.

ActionScript 3 Checkers game

For my studies,we learn actionscript3 in purpose to understand Object-oriented programming. I have to make a checkers games. I am lookinf for a checkers games source code in actionscript to try to understand how it works. My own version have a lot of bug and I can not make progress in programming because I don't know how make movement without bug. Could you give link to checkers games source code ? All the link, I found do not work. Thanks.

samedi 21 janvier 2017

(Actionscript 3.0) How to fix this arrow control glitch?

Currently, I am trying to make a game, but I ran into a couple of problems. One of them is that I have to click the screen for the arrow controls to work. Is there anyway to fix that?

Secondly, the arrow keys work as intended, but the WASD keys do not. Why is that?

private function key_down(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            leftPressed=true;  
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            rightPressed=true;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            upPressed=true;
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            downPressed=true;
        }
    }
    private function key_up(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            leftPressed=false;
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            rightPressed=false;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            upPressed=false;
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            downPressed=false;
        }
    }

Note: In another part of the code, I defined how the player moves if leftPressed, rightPressed, downPressed and upPressed is true or false.

Checking a Boolean variable in another class

Let me set the stage because it's too much code to post everything:

I have a Main.as that is setting up my SoundController.as so I can trigger sounds from any other class (SoundController.as has all the functions needed to call all my sounds as needed)

I have a ControlPanel.as that can access these sounds by using docRef.soundControl.laserFire or whatever other function name I want, and in this case the laserFire sound would trigger once.

So here is my question. I want to let this laser sound effect finish playing before you can fire another laser. So in SoundController.as I've set up the following pieces of code:

private var _laserPlaying:Boolean = false;

internal function laserFire():void {
    _sfxChannel = _laser.play(25);
    _laserPlaying=true;
    _sfxChannel.addEventListener(Event.SOUND_COMPLETE, laserFinished);
}

internal function laserFinished():void {
    _sfxChannel.removeEventListener(Event.SOUND_COMPLETE, laserFinished);
    _laserPlaying=false;
}

public function get laserPlaying():Boolean {
    return _laserPlaying;
}

public function set laserPlaying(value:Boolean):void {
    _laserPlaying = value;
}

Now in my enterFrameHandler function I want to do an

if (docRef.soundControl.laserPlaying()==false)

or something to that effect so I can check when the sound is done and allow the player to once again press the trigger to fire the laser. So far any variant I've tried on this either gives me an error (in this case 1195; Attempted access of inaccessible method laserPlaying through a reference with static type SoundController) or it actually compiles but after firing the first laser shot it never allows the trigger to be pressed again. So I'm obviously doing something wrong and am hoping someone can help.

Let me just state that the laser sound is playing just fine that first time, so don't worry about all the code I'm not bothering to show to make that portion of the code work. However, if more info is needed to understand how I'm making anything work just let me know. And Thanks in advance!

ActionScript 3 trying to clone google Halloween game

This past Halloween Google put out a game that used drawn symbols to initiate a function. Using a mouse or drawing table, the game would recognize x, o, <, >,- or |... each enemy had one or more of these symbols above them and had a hierarchy from left to right. As you drew a symbol each enemy with it as their left most would suffer an attack.

  1. Is this possible in actionscript 3? I can't find any resources to help

  2. If it is how complicated can the symbols be?

AS3: How would I make the answers pop up green or red if the answer was right or not in a quiz?

I got this code from my tutor and the quiz itself works; you can select answers and it traces that you've done so, but it doesn't recognise if you've pressed the right answer or not.

I want it to highlight green or red depending on if the right answer was clicked; but i don't know what code to right as i'm still a beginner at Action script. The correct answer is specified in the XML I just have to reference it to the code i think. Any help?

Here is the code:

package {

import flash.display.MovieClip;

import flash.text.TextField;

import flash.text.TextFormat;

import flash.text.TextFieldAutoSize;

import flash.net.URLLoader;

import flash.net.URLRequest;

import flash.events.Event;

import flash.events.MouseEvent;

import TabAnswer;

import IconNext;


public class Quiz extends MovieClip {

    private var tf:TextFormat = new TextFormat();

    private var question:TextField = new TextField();

    private var answer:TabAnswer;

    private var answers:Array = new Array();

    var answerArray:Array = new Array ("9","Pitcher");

    private var quiz:XML;       

    private var next:IconNext = new IconNext();

    private var currentQuestion:int = 0;


    public function Quiz() {
        // constructor code

        var xmlLoader:URLLoader = new URLLoader();

        xmlLoader.addEventListener( Event.COMPLETE, xmlLoaded );

        xmlLoader.load( new URLRequest( "quiz.xml" ) );

    }

    private function xmlLoaded ( e:Event ):void
    {

        // make an XML instance using XML data passed to this function
        quiz = new XML( e.target.data );

        trace( quiz );

        //set some text formatting

        tf.size = 20;

        tf.color = 0x000000;

        tf.font = "Tw Cen MT Condensed";    

        //create a textfield for question information

        addChild ( question );

        question.setTextFormat( tf );

        question.multiline = true;

        question.width = question.textWidth;

        question.autoSize = TextFieldAutoSize.LEFT;

        question.defaultTextFormat = tf;

        question.text = quiz.question[currentQuestion].description;

        for ( var a = 0; a < 4; a++ )           
        {

            var answer = new TabAnswer();

            answers.push( answer );

            addChild ( answers[a] );

            answers[a].x = question.x;

            answers[a].y = question.y  + question.height + answer.height + ( a * answer.height * 1.5 );

            answers[a].answer.text = quiz.question[currentQuestion].answers.answer[a];

            answers[a].addEventListener ( MouseEvent.MOUSE_DOWN, answerSelected );

        }

        addChild( next );

        next.x = stage.stageWidth - next.width * 1.3;

        next.y = stage.stageHeight - next.height * 2.3;

        next.addEventListener( MouseEvent.MOUSE_DOWN, nextQuestion );

    }

    private function answerSelected ( e:MouseEvent ):void
    {


        trace ( e.currentTarget.answer.text );




        //check to see if the answer that has been pressed, matches the
        //correctAnswer node in the quiz xml question

    }





    private function nextQuestion ( e:MouseEvent ):void
    {

        currentQuestion++;

        getQuestion( currentQuestion );


    }

    private function getQuestion( questionToGet:int ):void
    {

        question.text = quiz.question[questionToGet].description;

        for ( var a = 0; a < 4; a++ )           
        {                           

            answers[a].answer.text = quiz.question[questionToGet].answers.answer[a];

        }

    }

}

}

In AS3 how would i add 2 buttons that would enable the player to move on press instead of using the arrow keys?

I got this code off the internet for the game Pong to work on my AS3 document for my assignment. However i'm pretty much a beginner at code and i'm trying to get this game to work on mobile as the assignment needs a game to work on it. Because it uses arrow keys, i would like to basically just replace them with buttons instead, one for going up and one for going down. I just don't know the type of code that would allow me to do that. Something like, when button is pressed, player moves up or down depending which button, but im not sure where to replace the code and what to get rid of.

Here's the class file:

package {

import flash.display.MovieClip;

import flash.events.KeyboardEvent;

import flash.ui.Keyboard;

import flash.events.Event;

public class Pong extends MovieClip {
    //constants
    const ballspeed:int = 10;
    const playerspeed:int = 7;
    const computerspeed:int = 10;
    const computerIntelligence:int = 7;//intelligence is 7 out of 10

    //global variables
    var vx:int  = -ballspeed; // x component of velocity of ball (velocity is speed with direction)
    var vy:int  = ballspeed;  // y component of velocity of ball
    var v1:int  = 0;  // initial velocity of player
    var v2:int  = 0;  // initial velocity of computer
    var playerScore:int   = 0;
    var computerScore:int = 0;

var player:MovieClip = new PongPlayer()
var computer:MovieClip = new PongComputer()
var ball:MovieClip = new PongBall()

    public function Pong() {
    //init();       
    addEventListener(Event.ADDED_TO_STAGE, init);

    }
    //this function will add all event listeners
    function init(e:Event):void {
    stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDown);  // mouse events here
    stage.addEventListener(KeyboardEvent.KEY_UP,KeyUp);
    stage.addEventListener(Event.ENTER_FRAME,EnterFrame);

    addChild ( player );
    addChild ( computer );
    addChild ( ball );

    player.x = 23
    player. y = 300

    computer.x = 637
    computer. y = 311

    ball.x = 308
    ball. y = 328

    }
    // this function resets the game
    function reset():void {
        player.y   = stage.stageHeight/2;
        computer.y = stage.stageHeight/2;
        ball.x     = stage.stageWidth/2;
        ball.y     = stage.stageHeight/2;
        if(Math.abs(Math.random()*2) > 1){
        vx = -ballspeed;
        }else{
        vx = ballspeed; 
        }
        if(Math.abs(Math.random()*2) > 1){
        vy = -ballspeed;
        }else{
        vy = ballspeed; 
        }
    }
    //this function sets the velocity of player when key is pressed  // start drag with mouse down
    function KeyDown(event:KeyboardEvent):void {
        if(event.keyCode == Keyboard.UP) {
            v1 = -playerspeed;
        }else if(event.keyCode == Keyboard.DOWN) {
            v1 = playerspeed;
        }
    }
    //this function sets the velocity of player to 0 if key is released // Stopdrag here
    function KeyUp(event:KeyboardEvent):void {
        if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN) {
            v1 = 0;
        }
    }

    //This function is executed when a frame changes
    function EnterFrame(event:Event):void {
        //variable decleration
        var pHalfHeight = player.height/2; // half height of player(used for collisions)
        var pHalfWidth  = player.width/2;   // half width of player (used for collisions)
        var bHalfHeight = ball.height/2; // half height of ball(used for collisions)
        var bHalfWidth  =  ball.width/2;   // half width of ball (used for collisions)

        //moving the player
        player.y += v1;
        //limiting the motion of player (it should not move beyond the stageheight)
        if(player.y + pHalfHeight > stage.stageHeight) {
            player.y = stage.stageHeight - pHalfHeight;
        }else if(player.y - pHalfHeight < 0) {
            player.y = 0 + pHalfHeight;
        }

        //moving the ball
        ball.x += vx;
        ball.y += vy;

        //moving the computer automatically
        if(Math.abs(Math.random()*10) < computerIntelligence){
            var d:int = computer.y - ball.y;
            if(Math.abs(d) > pHalfHeight){
                if(d>0) {
                    v2 = -computerspeed;
                }else{
                    v2 = computerspeed;
                }
            }
        }
        computer.y += v2;
        //limiting the motion of computer (it should not move beyond the stageheight)
        if(computer.y + pHalfHeight > stage.stageHeight) {
            computer.y = stage.stageHeight - pHalfHeight;
        }else if(computer.y - pHalfHeight < 0) {
            computer.y = 0 + pHalfHeight;
        }

        //collision with horizontal walls
        if(ball.y + bHalfHeight >= stage.stageHeight || ball.y - bHalfHeight <= 0) {
            vy *= -1;
        }

        //collision with player and computer
        if(ball.x - bHalfWidth <= player.x + pHalfWidth) {
            if(Math.abs(ball.y - player.y) <= pHalfHeight) {
            vx = ballspeed;
            if(v1!=0){
                vy = 2*v1;
            }
            }
        }else if(ball.x + bHalfWidth >= computer.x - pHalfWidth) {
            if(Math.abs(ball.y - computer.y) <= pHalfHeight) {
            vx = -ballspeed;
            if(v2!=0){
                vy = v2;
            }
            }
        }

        //collision with vertical walls & updating scores
        if(ball.x + bHalfWidth >= stage.stageWidth) {
            playerScore += 1;
            reset();
        }else if(ball.x - bHalfWidth <= 0) {
            computerScore += 1;
            reset();
        }

        //display the score on the textfield
        //txtPlayer.text  = String(playerScore);
        //txtComputer.text = String(computerScore);
    }
}

}

When would you use hasOwnProperty on an array?

I have just seen an example where the code is as follows:

var schemaSet:Array = currentScope();
if (schemaSet.hasOwnProperty("current"))
    schema = schemaSet["current"];

I have never seen this before. I checked the as3 docs and didn't find any information on it. When and where would you use this? Is this better than or equivalent to:

if (schemaSet.indexOf("current")!=-1)

vendredi 20 janvier 2017

AS3 / AIR, make a dynamic txt clickable to load a saved progress

I want to make a list of users in an Android application (in a dynamic txt bow or you may suggest one) when the user click his name on the list, a button will appear so that his/her previous progress will be loaded. It is created in Adobe Flash AIR using Actionscript 3. I don't know where to start. You may comment your email and i will send to you my sourcefile. Thanks!

How do i create a gravity flipping mechanic (ActionScript 3)

This is the theory I have in my head. I have a movieclip and its always falling/this.y + dy. But once it collides with the platform dy will be set to 0 so it will stop falling. Then when i press the space bar, dy will be set to 3 again but it will multiply by -1 so it will start flying upwards instead.

This is what i have so far

package  {
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;

public class Player extends MovieClip{
    //Properties
    private var moveLeft:Boolean;
    private var moveRight:Boolean;
    private var gravity:Boolean; //Switches gravity
    private var dx:Number //Speed of player moving on X axis
    private var dy:Number //Speed of player moving on Y axis
    private var level:MovieClip;
    private var platforms:Array;
    private var tilesTop:Array;
    private var tilesBtm:Array;
    private var tilesLeft:Array;
    private var tilesRight:Array;
    private var grounded:Boolean;
    private var flipGravity:Number;

    //Constructor
    public function Player(iMain:Main) {
        level = iMain.getLevel();
        platforms = level.getPlatforms();
        tilesTop = level.getTilesTop();
        tilesBtm = level.getTilesBtm();
        tilesLeft = level.getTilesLeft();
        tilesRight = level.getTilesRight();

        dx = 10;
        dy = 10;
        flipGravity = -1;
        this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
    }

    //Methods
    // Method: Add to stage handler
    private function addedToStageHandler(evt:Event):void {
        this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
        this.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
    }

    //Methods: Key down handler
    private function keyDownHandler(evt:KeyboardEvent):void {
        if (evt.keyCode == Keyboard.LEFT) {
            moveLeft = true;
        }
        else if (evt.keyCode == Keyboard.RIGHT) {
            moveRight = true;
        }
        else if (evt.keyCode == Keyboard.SPACE) {
            if (gravity) {
                gravity = false;
            }
            else if (!gravity) {
                gravity = true;
            }
        }
    }

    //Methods: Key up handler
    private function keyUpHandler(evt:KeyboardEvent):void {
        if (evt.keyCode == Keyboard.LEFT) {
            moveLeft = false;
        }
        else if (evt.keyCode == Keyboard.RIGHT) {
            moveRight = false;
        }
    }

    //Methods: Move player
    public function movePlayer() {

        // Move downward
        this.y += dy;

        grounded = false;

        // *** Player's collision tests
        // Check if it lands on platform
        landOnPlatform();

        // Move left
        if (moveLeft) {  // equivalent to if (moveLeft == true)
            if (this.x > 200) { //move player
                this.x -= dx;
            }
            else {
                level.moveLevel(dx);
                if  ( level.x >= 0 ) {//stage stop moving so that the player won't fall of the screen(left)
                    level.x = 0;
                    this.x -= dx;
                    if  (this.x < this.width/2) {
                        this.x=this.width/2;
                    }
                }
            }
        }

        // Move right
        if (moveRight) {
            if (this.x < 600) { //move player
                this.x += dx;
            }
            else {
                level.moveLevel(-dx);
                if (level.x <= -1600) { //stage stop moving so that the player won't fall of the screen(right)
                    level.x = -1600;
                    this.x += dx;
                    if  (this.x > stage.stageWidth - this.width/2) {
                        this.x= stage.stageWidth - this.width/2;
                    }
                }
            }
        }

        //Gravity flip
        if (!gravity) {
            dy * flipGravity;
            grounded = false;
        }
    }

    private function landOnPlatform() {
        for (var i:int=0;i<platforms.length;i++) {
            /*if (this.hitTestObject(platforms[i])) {
                dy = 0;
                grounded = true;
                this.y = platforms[i].y;
                break;
            }*/
            if (this.hitTestObject(tilesTop[i])) {
                dy = 0;
                grounded = true;
                this.y = tilesTop[i].y;
                break;
            }

            else if (this.hitTestObject(tilesBtm[i])) {
                dy = 0;
                grounded = true;
                this.y = tilesBtm[i].y;
                break;
            }

            else if (this.hitTestObject(tilesLeft[i])) {
                dy = 0;
                grounded = true;
                this.x = tilesLeft[i].x;
                break;
            }

            else if (this.hitTestObject(tilesRight[i])) {
                dy = 0;
                grounded = true;
                this.x = tilesRight[i].x;
                break;
            }
        }
    }
}
}

This is the player class above

I have a gameloop running in the main class and its calling the function of move player.