jeudi 30 juin 2016

Modify a variable when an event is triggered in AS3

I am trying to code a simple notification class in as3, it as just two buttons, one for "ok", one for "cancel", so there is one event listener for each buttons.

The problem is that I want a variable to be passed from the main class to the notification class, then to be returned to the main after one of the eventListener has been triggered by the user.

I have tried differents things but no one seems to work, I am sure there is a common and simple way to do that but I am new to the language.

Thanks, and sorry for my english.

Array of months AS3 DATE()

I'm working on a stats page which shows a rolling 12 months of figures. I've created an array to hold the months and a for loop to populate the array starting with the current month as first element in the array

var myDate:Date = new Date();
for(var mn:uint=0; mn<12;mn++){
    myDate.setMonth(myDate.getMonth()+1);
    trace("statMonth +: "+ myDate.month);
    }

The trace produces this:

staMonth: 6 staMonth: 7 staMonth: 8 staMonth: 9 staMonth: 10 staMonth: 11 staMonth: 0 staMonth: 2 staMonth: 3 staMonth: 4 staMonth: 5 staMonth: 6 staMonth: 7

I had to do a double take.. Where is month 1? Is it me? Am I being totally stupid?

mercredi 29 juin 2016

hitTestObject not working properly AS3

How to make the objects detect each other without having to be so accurate? Currently, the program that I'm working on only allow the items to be matched when it is accurately matched at the upper left edge but i did not use hitTestPoint, I used hitTestObject. Below are my codes.

if (bin1.hitTestObject(item)){ 
        updateShape(item, bin1);

Translate script from Actionscript to Javascript

I have bben looking for a function but the only solution I found is in Actionscript but I need it in Javascript. The original post is here. The General idea is this: I have a serie of points, those points makes a polygon, then I have another point, the script should answer if the new point is inside the polygon. Here is an example from the site where I found the function showing 4 polygon that turn green when you click ouside and blue inside. =)

enter image description here

/**
* Funcion que determina si un punto(X,Y) se encuentra dentro de un poligono
* @pointList Array de puntos Ej.: Array[ (0,0) , (100,50), (34,67) ]
* @p Punto(X,Y)
*/
function insidePolygon( pointList , p )
{
   var counter = 0;
   var i;
   var xinters;
   var p1  = new punto(0,0);
   var p2 = new punto(0,0);
   var n = pointList.length;

   p1 = pointList[0];
   for (i = 1; i <= n; i++)
   {
      p2 = pointList[i % n];
      if (p.y > Math.min(p1.y, p2.y))
      {
         if (p.y <= Math.max(p1.y, p2.y))
         {
            if (p.x <= Math.max(p1.x, p2.x))
            {
               if (p1.y != p2.y) {
                  xinters = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
                  if (p1.x == p2.x || p.x <= xinters)
                     counter++;
               }
            }
         }
      }
      p1 = p2;
   }
   if (counter % 2 == 0)
   {
      return(false);
   }
   else
   {
      return(true);
   }
}

Change colors of an image from a url using actionscript filter?

Hi I want to use the site http://wonderfl.net/ to change the color of an image specifically using AS3 filters. I am kind of lost where to start. I want the as3 to make a small program that loads an image based on the url and then you can use sliders to change Saturation, Contrast, Brightness, Hue, offsets and multipliers for Red, Green and Blue.

Please help! Thank you in advance.

Remove Air for Android StageWebView Server Unverified Pop UP

I'm developing an Adobe Air For Android app using AIR SDK 21. In the app I am using the AS3 StageWebView class to display web content to our users. What I am running into is that certain websites prompt the user with the following message in a pop up:

"The server that the application is connecting to is unverified" "Certificate: ,etc" "Trust for Session, Cancel"

I am assuming this is a https/certificate issue, is there any way to remove this popup or instruct the app to just accept the connection?

Any help would be appreciated as this is happening on multiple sites and making the user experience unpleasant.

Thanks

Should I learn Actionscript 3 along with Javascript to make web games?

Hello(my first post on stack overflow) I wanted to ask that should I learn Actionscript 3 or not, Am Already learning Javascript on Codecademy (20% completed). Someone suggested me to learn AC 3 and get the Flixel tuotorials on new grounds,Should I learn AS3 along or just focus on JS. Purpose for learning a language is to make 2d scroller web games,that works on smart phones and tablets.

mardi 28 juin 2016

AS3 working with lots of text inputs?

I want to setup a Flash piece that has a bunch of user input fields, and several dynamic text fields that update based on what gets input.

What is the most efficient type of listener to use that will get triggered after any input field gets tabbed, or clicked away from?

I don't want to have to set up a focus_out for everyone of my input fields. I just want one function to tell all my variables to update any time an input gets changed...

Not sure if this helps or complicates things, but most all of my inputs/dynamics are nested inside an MC. Each MC has a subject field, and 7 other inputs, and 6 dynamic variables. Then I want to be able to duplicate that whole shebang multiple times...

Thanks for any suggestions. Especially typed out code suggestions as I am more or less an AS3 noob.

How to decrease volume in a loop?

How would someone change sound levels of a music playing in a loop? For example, I'm making a game and at a certain frame I want the music level (music.wav) to be decreased to half of its volume.

How could someone do this in AS3?

Actionscript-3 Looping

my employer decided they wanted me to start doing animation with Adobe's new "Animate CC" application. My issue is that I don't know how to loop my animation outside of the Adobe Animate environment. I have never worked with this program before, nor have I used (or even heard of) ActionScript, so I will probably need the most basic of answers to understand what's going on.
For context: my project has about 100 layers of content and I have no idea how this application works.

Basically, how do I use Action-Script in Adobe Animate CC in order to infinitely loop my animation until closed?

Thanks everyone.

Creating First Person Controls in Actionscript 3

I'm trying to make first person movement controls for a simple FPS I'd like to make in flash, but I'm struggling with directional movement.

Summery: I'd like to be able to create FPS controls in flash, but can't seem to get it right.

Details: I'm using a method by which rotations are applied to a movieclip (mc) that remains stationary with its pivot point underneath your point of view, so that the world seemingly rotates around you when the mouse is moved.

I then apply directional movements to a moveclip (box) nested within the rotating movieclip (mc) to give the illusion of walking around in a first person view.

mc - Handles rotation (a container for box)

-----box - Handles translation (box serves as the floor, so I have it as a black square)

The problem begins when you rotate mc and begin moving with the arrow keys. box's translation doesn't take mc's rotation in consideration, and so you're still locked to the x and y axis of box so, no matter where you face, you're always locked onto those axis as opposed to the traditional move forward wherever you're facing that most FPS games employ.

I haven't a clue of where to go from here, so any help would be greatly appreciated. :3

Timeline code:

//You’ll need a symbol named mc. With another symbol named box within it.
//mc should be centered on the stage.
//stage size 1920x1080


var mL: Boolean = false;
var mR: Boolean = false;
var mD: Boolean = false;
var mU: Boolean = false;

var speed: int = 10;

mc.rotationX=90;
mc.y=1000;

mc.x=932.1;
mc.z=0;
mc.width=980;
mc.height=98;



stage.addEventListener(Event.ENTER_FRAME, EF);

function EF(e: Event): void {
//Rotates mc based on distance of mouseX to the center of the stage.
    if(mouseX<stage.stageWidth){
        mc.rotationY += speed*((mouseX-stage.stageWidth/2)*.0001);
    }
    if(mouseX>stage.stageWidth){
        mc.rotationY += speed*((mouseX-stage.stageWidth/2)*.0001);
    }


//Arrow key controls.
    if (mL == true) {
        mc.box.x += speed;
    }
    if (mR == true) {
        mc.box.x -= speed;
    }
    if (mD == true) {
        mc.box.y += speed;
    }
    if (mU == true) {
        mc.box.y -= speed;
    }

}

stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
function kD(e: KeyboardEvent): void {
//Key down conditionals.
    if (e.keyCode == Keyboard.LEFT && mR == false && mD == false && mU == false) {
        mL = true;
    }
    if (e.keyCode == Keyboard.LEFT && mR == false && mD == false && mU == true) {
        mL = true;
        mU = true;
    }
    if (e.keyCode == Keyboard.UP && mR == false && mD == false && mL == true) {
        mL = true;
        mU = true;
    }
    if (e.keyCode == Keyboard.LEFT && mR == false && mD == true && mU == false) {
        mL = true;
        mD = true;
    }
    if (e.keyCode == Keyboard.DOWN && mR == false && mU == false && mL == true) {
        mL = true;
        mD = true;
    }


    if (e.keyCode == Keyboard.RIGHT && mL == false && mD == false && mU == false) {
        mR = true;
    }
    if (e.keyCode == Keyboard.RIGHT && mL == false && mD == false && mU == true) {
        mR = true;
        mU = true;
    }
     if (e.keyCode == Keyboard.UP && mL == false && mD == false && mR == true) {
        mR = true;
        mU = true;
    }
    if (e.keyCode == Keyboard.RIGHT && mL == false && mD == true && mU == false) {
        mR = true;
        mD = true;
    }
    if (e.keyCode == Keyboard.DOWN && mL == false && mU == false && mR == true) {
        mR = true;
        mD = true;
    }


    if (e.keyCode == Keyboard.UP && mR == false && mD == false && mL == false) {
        mU = true;
    }
    if (e.keyCode == Keyboard.DOWN && mL == false && mR == false && mU == false) {
        mD = true;
    }


}

stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kU(e: KeyboardEvent): void {
//Key up conditionals.
    if (e.keyCode == Keyboard.LEFT) {
        mL = false;
    }
    if (e.keyCode == Keyboard.RIGHT) {
        mR = false;
    }
    if (e.keyCode == Keyboard.UP) {
        mU = false;
    }
    if (e.keyCode == Keyboard.DOWN) {
        mD = false;
    }
}

Int variable not changing

I'm trying to increment my int variable i when a button is pressed. However, it's not working.

var i:int = 0;

DB_47_ENTER_ROOM105.addEventListener(MouseEvent.CLICK, DB_47_ENTER_ROOM105_Action);

function DB_47_ENTER_ROOM105_Action(event:MouseEvent):void {
    trace(i);
    if (i == 0) {
        gotoAndStop(49);
        i = 1;
    }

    if (i == 1) {
        gotoAndStop(50);
    }
}

AS3: draw 2d DisplayObjects UNDER stage3ds

Is there any way to draw 2d DisplayObjects UNDER stage3ds? I mean, flash' stage is allways upper stage3ds: enter image description here Can I create another stage below Stage3D[0]? Or any other way?

AS3 code, Wheel of Fortune spinning game

I'm working on wheel of fortune game. Currently the spinning time of the wheel depends from the time the button is pressed. Longer you hold, the harder you spin.

I need the wheel to spin for 4 to 5 seconds after the button is pressed, with ease in/out effect and to stop on a random sector each time. Here is the code:

import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;
import fl.transitions.Tween;
import fl.transitions.TweenEvent;
import fl.transitions.easing.*;


var spinning:Boolean = false;
var spinTween:Tween;
var startTime:Number;
spin_bnt.addEventListener(MouseEvent.MOUSE_DOWN, setStartTime);
spin_bnt.addEventListener(MouseEvent.MOUSE_UP, spinWheel);
function setStartTime(e:MouseEvent) {
startTime = getTimer(); 
}
function spinWheel(e:MouseEvent) {
if (!spinning) {
    spinning = true;
    var spinTime = Math.min(12.2, Math.max(2.12, ((getTimer() - startTime) / 100)));
    var endRot = Math.round((spinTime * 360) + (Math.random() * 360));
    spinTween = new Tween(wheel_mc, "rotation", Regular.easeOut, wheel_mc.rotation, endRot, spinTime, true);
    spinTween.addEventListener(TweenEvent.MOTION_FINISH, spinTween_finished);
}
}
function spinTween_finished(e:TweenEvent):void
{
spinning = false;
}

Actionscript 3 gotoAndStop in a branching storyline

I have created a simple gotoAndStop storybook in Flash but it's following branching storyline. The knight entered a castle and there is one gate. Upon entering the gate, he faced 3 more doors and each door, leads to another series of rooms.

However, the end will be the same. It appears to be a simple "gotoAndStop" codes but at the end of the of the story, the knight will earn some sort of price (represented by a frame) depending on which doors he entered. My question is, how will I know which buttons the user clicked so that i can "gotoAndStop" him to a certain frame? The final destination or award frame of user depends on which buttons he clicked.

This is my sample gotoAndStop code that I used in the storybook(similar code I used in all frames, just changing the button instance names, function names and frame labels):

nextbutton1.addEventListener(MouseEvent.CLICK, proceedDoor1);
function proceedDoor1 (e:Event){
    gotoAndStop("door1")
}

I am complete novice so please bear with me. Thanks!

How to disable Rewind/Forward options?

You know when you right-click on a scene and a bunch of options pop up? How do you disable the rewind and forward options (in-case a user accidentally presses on one of those options) because it screws my whole Flash game up.

lundi 27 juin 2016

Flex/AS3 Change a variable

I have this code. I need change variable DiagnosIsWritten=true, when input_diagnos (TextInput) is written something. Can you help me to say all ways, how i can do it.

<fx:Script>
        <![CDATA[
        public var DiagnosIsWritten:Boolean;
</fx:Script>

<s:DataGrid id="examsDG" >
      <s:columns>
            <s:ArrayList>
                <s:GridColumn  editable="true" headerText=" width="156" 
  itemRenderer="modules.PatientCardModule.moduls.ToothModule.renderers.examsDG_BiteRenderer"/>
    </s:ArrayList>
    </s:columns>
</s:DataGrid>


examsDG_BiteRenderer.mxml : 
<s:TextInput id="input_diagnos" text="test" width="100%" height="100%" />

Cloning drag and drop, snap to grid

Im a beginner at ActionScript3 and Im trying to create a a game where by the user is able to duplicate an object using the drag and drop method, and is still able to reposition the duplicates that snap to grids-

Cube_1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
Cube_1.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler1);

function mouseDownHandler1(evt:MouseEvent):void {
    var object = evt.target;
}

function mouseUpHandler1(evt:MouseEvent):void {
    var obj = evt.target;
        obj.stopDrag();
}

I managed to find these codes but but Im unable to make it duplicate as Im unsure of how to go around doing so. Are there any ways I can improve on this?

Thankyou!

AS3 Security sandbox violation when loading data from https

When trying to load data that sits on an https domain (that I have no control over), I get this:

Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: http://localhost:3400/bin-debug/Player.swf cannot load data from https://[url].xml

I'm using FlashBuilder 4.6.

I've tried other solutions, but they don't seem to help or be applicable.

I've gone to the global settings manager and allowed my swf, the swf's directory, the site I'm trying to hit, localhost, and more. I've also gone to the local settings manager and done the same.

I've added Security.allowDomain("*"); and Security.allowInsecureDomain("*"); but that didn't help either.

Is there anything I can do?

actionscript 3 air for android encrypted local storage data lost after upgrade

I've developed 2 mobile apps for ios and android with animate CC and as3/ adobe AIR.

The apps use AIR's encrypted local storage (ELS) to remember user settings and bypass a registration screen after first time login. This works fine on ios (on both apps), so that even if a user uninstalls the app, then reinstalls later, the settings are remembered.

On android, the app resets itself every time - i.e. it seems that it is unable to access the ELS.

Permissions are set in the manifest as follows:

<android>

   <manifestAdditions><![CDATA[<manifest>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>]]></manifestAdditions>
  </android>
  <versionLabel></versionLabel>

I have been unable to find any other cases like this on the website that apply specifically to Android, though the question was also asked in this thread, it offered suggestions that should work for both ios/android and ultimately these don't seem to apply to my particular case :(

I need Adobe AIR For Android Encrypted Local Store or Application Storage data to persist even after uninstalling or updating the app.

I have had a few experienced as3 coders look into this, and the code seems to be correct, and it's quite possibly permissions related.

I also attempted to use a work around (where a directory is created, and data is stored in there). Apparently, this work around code has been used on several Flex apps and works, but even so, the same problem of the app resetting data still happens. (this could hint at it being an animate cc bug, or a permissions setting thing, perhaps?)

I've tried with a few different SDKs as well (20,21,22) and no joy. Still racking my brains! Any help much appreciated!

Thanks.

Is it possible to stop word wrap in as3 textarea spark component?

I want to stop the word wrap "i.e long words should not be able to be broken and wrap onto the next line" in textarea spark component.

So anybody have an idea how to do this?

Load ttf font in runtime in as3

I have been trying to run a flash application in firefox , what am trying to do is i have a textfield and a button and i will be needed to load a ttf that is given on the textfield by the user

i need to load the ttf and embed/register the font in the application, so that i can use it , i have already tried a runtime ttf loader class but it is not working ! as we cant use embedFonts becuse the url will be always dynamic and produced on runtime.

I am in kind of a deadline , so any suggestion would be more than helpful!

dimanche 26 juin 2016

Swipe gesture does not function

I am developing a mobile apps with swipe gesture. User need to swipe to the left in order to view the list of contents. Then, when user click one of the content, there will be list of sub content and here is the problem. User supposedly can scroll the sub content, but this is not working. Here, I attached together with my .fla and Im developing the app by using Actionsript 3, Android Air. Anyone please help me what should I alter..? Thank you.

How to change bitmapdata in AS3

I'm building a spritesheet class. Hopefully this will be low hanging fruit to someone, but I'm stumped.

I have a spritesheet (.png) that I've loaded at runtime and placed a section of it on the stage using this code from within the Spritesheet class .as file ouside of the constructor method:

        private function onLoad(e:Event):void
    {
        var loaderBmp:Bitmap = Bitmap(_loader.content);
        _bmpData.copyPixels(loaderBmp.bitmapData, new Rectangle(0,0,80,80),new Point(0,0));
    }

That works fine. I get my slice of the .png file displaying nicely. In my case, the spritesheet is meant for animating a character, so I need to update the BitmapData and I'm not having any luck. Here is what I'm trying this within my Main class in a function I use to alter the frame of the animation depending on the state of the character:

c._spriteSheet._loader.content.bitmapData.copyPixels(loaderBmp.bitmapData, new Rectangle(0,20,50,30),new Point(0,0));

c is a reference to the Runner object that is the character.

_spriteSheet is a property of the Runner class of type Spritesheet.

_loader is a property of the c._spriteSheet and is the Loader object used when the spritesheet was instantiated.

It doesn't throw an error, but it also doesn't replace the original bitmapData object with the new one. I thought maybe this meant that I need to create a new BitmapData object and use that in the copyPixels method, but that returned the same results (nothing). When I step through the code in debug mode, everything looks like it is working, but my display object does not update with the new bitmapData. What am I tripping on?

Thanks for looking!

as3 - contact form not working

I know this question has been asked a couple of times, but I cant make a contact form using as3 and php i always get an "UnidentifiedIndex"error ,here is the code . PHP:

<?php
{
$to = "name@yourdomain.com";
$subject = ($_POST['senderName']);
$message = ($_POST['senderMsg']);
$message .= "\n\n---------------------------\n";
$message .= "E-mail Sent From: " . $_POST['senderName'] . " <" . $_POST['senderEmail']  . ">\n";
$headers = "From: " . $_POST['senderName'] . " <" . $_POST['senderEmail'] . ">\n";
if(@mail($to, $subject, $message, $headers))
{
echo "answer=ok";
} 
else 
{
echo "answer=error";
}
}
?>

Action Script:

submit_btn.addEventListener(MouseEvent.CLICK, sendMessage);
function sendMessage(e:MouseEvent):void
{
    var my_vars:URLVariables = new URLVariables();
    my_vars.senderName = name_txt.text;
    my_vars.senderEmail = email_txt.text;
    my_vars.senderMsg = message_txt.text;


var my_url:URLRequest = new URLRequest("mail.php");
my_url.method = URLRequestMethod.POST;
my_url.data = my_vars;

var my_loader:URLLoader = new URLLoader();
my_loader.dataFormat = URLLoaderDataFormat.VARIABLES;
my_loader.load(my_url);

name_txt.text = "";
email_txt.text = "";
message_txt.text = "Message Sent";

}

By the way i am completely new to PHP

And this code i got it from a website so it is not mine and i am using xampp to create the server to open the php file can u help me? And another question , Will this work on mobile if i keep the server running? Thanks,

samedi 25 juin 2016

AS3 Loading dynamically named text files

I have a preload movie that loads an interface. In the interface I have many buttons. When I click on a button I want to load a text file into a movie called "TextMovie.swf". I want to be able to click on a button, take the name of the button and load a text file that is the same name as the button instance, and have the window appear close to the mouse click. There will be hundreds of buttons and hundreds of text files. I'm sure this is easy for some. Here is the loader for a button:

button_1.addEventListener(MouseEvent.CLICK, fl_ClickToPosition_2);

function fl_ClickToPosition_2(event:MouseEvent):void 
{
var my2ndLoader:Loader = new Loader();
var url2:URLRequest = new URLRequest("TextMovie.swf");
my2ndLoader.load(url2);
addChild(my2ndLoader);
my2ndLoader.x = 200;    
my2ndLoader.y = 10;

}

Then in the TextMovie.swf I have:

import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.StyleSheet;

var css:StyleSheet = new StyleSheet();
css.setStyle("a:hover", {textDecoration:"underline"});

var textLoader: URLLoader = new URLLoader();
textLoader.dataFormat = URLLoaderDataFormat.VARIABLES;

textLoader.addEventListener(Event.COMPLETE, textLoaded);

loadText();

function textLoaded(evt: Event): void {
title_txt.htmlText = textLoader.data.txtTitle;
main_txt.htmlText = textLoader.data.txtBody;
URL_txt.htmlText = textLoader.data.txtURL;
URL_txt.styleSheet = css
}

function loadText(): void {
// var fileName: String = "assets/test_01.txt";
var fileName: String = "assets/" +  +  ".txt";
textLoader.load(new URLRequest(fileName));
}

I'm not sure how to get the name of the button I pushed and apply it to the string that will load the correct text file. I also can't get the window to appear close to the mouse click. Right now I just have it set with an x and y for testing.

I know it's a lot but thanks for any help.

AS3 - How to recive information from client using the app?

I am currently working on an air app in as3,

What I want to do is that I want the user of the app to fill in textfields and I want to recive those text fields and I don't know how do I start and I don't know how am I going to recive those textfields? can you help me?

As3 hitTestObject not working

My hittestobject isn't working and I don't know why. Could anyone please help me? I'm trying this all day already.

Why doesnt it work?

`

for(var id=0; id<5; id++) {

        var frizercek:obstacle = new obstacle();

        //setting the brick's coordinates via the i variable and brickRow
        frizercek.x = frizercek.x + id* 110;
            frizercek.gotoAndStop(3)
            frizercek.width = 92.9
            frizercek.height = 26.1

            line4.addChild(frizercek);

            trace("lol" + id)
            frizercek.addEventListener(Event.ENTER_FRAME, didithit ); 

        function didithit(e:Event){
            if(mcball.hitTestObject(frizercek)){
                    ballYSpeed  *=-1;
    line4.removeChild(frizercek)


            }
            if(mcball.hitTestObject(frizercek.sidewall)){
                    ballXSpeed *=-1;
    line4.removeChild(frizercek)


            }

        //finally, add the brick to stage

    }


    } `

vendredi 24 juin 2016

I want to make android (Android / Backscript.A) script which can automatically execute commands and perform actions

I want to make android (Android / Backscript. A) script which can automatically execute commands and perform actions.

AS3 removing an event handler within a function

I am adding an eventListener within the first function and wish to get rid of it in the second. Removing the eventListener doesn't seem to be working and as such each subsequent call to the first function is adding more event handlers. I know one way to get around this is to not add the eventListener within the function, but doing it this way will save me a lot of work for the rest of the code. Any ideas?

function errorBoxHandler(event:Event):void
{
this.errorBox.errorOkBtn.addEventListener(MouseEvent.MOUSE_DOWN, function(event:MouseEvent){errorBoxOkHandler(event, btnSelected,listIndexNum)});
}

function errorBoxOkHandler(event:MouseEvent, btnSelected:String, listIndexNum:int):void
{   
this.errorBox.errorOkBtn.removeEventListener(MouseEvent.MOUSE_DOWN,errorBoxOkHandler);
}

'Unable to invoke CFC - The data for must be no more than 100 characters in length

I'm trying to call a method as follows:

<cfinvoke component="#variables.target#"
                      method="#arguments.methodName#"
                      argumentcollection="#arguments.args#"
                      returnvariable="rtn">
            </cfinvoke>

However, i have the following error:

'Unable to invoke CFC - The data for 'param_value' must be no more than 100 characters in length.' faultDetail:''

arguments.args it is a struct and one of his elements looks like this :

{ param_name: 'property_uid', param_value : '00000000-0000-0000-0000-0000000213131200,00002131300-0000-0000-0000-000000000000,00000000-0000-0000-0000-0000000002122,00000000-0000-0000-0000-000000032242 }

I know the problem it is because of this element but I don't know how to fix. Note that I've updated the Maximum number of POST request parameters from 100 to 300 in CF administrator

Unity BlendMode

Im pretty new to unity and i had written a simple 2 layer day night system in flash AS3. But im not sure how i could achieve the same thing in unity

This is the AS3 code i was using. It simply adds a black square to the back ground with addNight(). Then addLight() adds a gradient circle to the screen. The effect of light/dark is achieved with

spr.blendMode = BlendMode.LAYER;

and

bound.blendMode = BlendMode.ERASE;

  • Im currently working with c# in unity

    public var spr:Sprite = new Sprite();
    var msk:Sprite = new Sprite();
    
    
    private var gType:String;  
    private var matrix:Matrix;  
    
    private var bound:Sprite;
    
    
    
    public function addNight()
    {
        spr.alpha = .85;
    
        spr.graphics.beginFill(0x000000);
        spr.graphics.drawRect(0,0 ,800,600);
        spr.graphics.endFill();
    
        prnt.addChild(spr);
    
        spr.blendMode = BlendMode.LAYER;
    }
    
    
    
    public function addLight(x:int, y:int)
    {
        var gType:String = GradientType.RADIAL;  
    
        var matrix:Matrix = new Matrix();  
        matrix.createGradientBox(300,300,0,0,0);    
    
        var gColors:Array = [0xFFFFFF, 0x000000];  
        var gAlphas:Array = [.9,0];  
        var gRatio:Array = [0,255];  
    
        var bound:Sprite = new Sprite();  
        bound.graphics.beginGradientFill(gType,gColors,gAlphas,gRatio,matrix);  
        bound.graphics.drawCircle(150,150,150);
        bound.x = bound.y = 0;  
    
        bound.x = x;
        bound.y = y;
        bound.blendMode = BlendMode.ERASE;
        spr.addChild(bound);
    }
    
    

I should also mention, i'm working with Unity2D. Im also willing to use a completely different way of achieving a lighting system

External SWF not loading when not testing in flashdevelop

What I mean is that when I test it in flashdevelop, the External SWF loads, but when I have the main SWF outside of the project, it won't load. (eg: if I have the main SWF on my desktop, it won't work)

So, I'm trying to make a simple thing where when I click a button, it loads an External SWF.

Here's the function for loading the External SWF:

    public function loadPart(part:String)
    {
        if (loader.numChildren > 0)
            loader.removeChildren(0);
        stage.addChild(loader);
        trace(part)
        loader.load(new URLRequest("../src/"+part+".swf"));
        stage.addChild(medButton)
        stage.addChild(slowButton)
        stage.addChild(fastButton)
    }

part being the name of the SWF

This works fine when I test in flashdevelop, but if I clone the SWF in the bin folder of the project folder to the desktop, it won't work. It also works if I just open the SWF in the bin folder.

Anyone know why this is happening?

FlashBuilder - Errors that only I get and no one else does

I work for a company that develops both Mobile (C# with Unity) and Facebook (AS3 with Flashbuilder) apps. To my knowledge, everyone is using the same versions of the IDEs and SDKs associated. I have now encountered 2 separate errors that only I get and nobody else (a team of about 30) get.

First error, we had couple of functions in our C# code that were translated to AS3. C# allows overloaded functions, while AS3 does not, so when we ported to AS3, we had to pick one of the following:

Object.SetMidposition(float x, float y);
Object.SetMidposition(Point point);

got translated into AS3 as:

Object.SetMidposition(x:Number, y:Number)

However, there were a couple of spots in our code base where the translation missed converting the Point to an x,y pair, so we had a call where it was trying to Object.SetMidposition(Point) when it was looking for (x,y). This should have errored out for everyone, but for some reason only errored out for me. I have no idea why it only broke for me, and no one else.

Second error, a developer made an if statement with an XOR comparison:

if(boolA ^ boolB)
{
 //Do stuff
}

I looked up the ^ operator, and it is indeed an XOR, and this should work. And it does! For everyone except me. In my environment, I get an error at this line saying that I cannot implicitly convert booleans to Numbers. I have no idea why it thinks I am trying to convert booleans to Numbers, or why I am the only one who is having this issue.

So an error that should have broke everyone, but only broke me, and another error that should not break anyone, but breaks me.

What gives? Thanks in advance.

How to load a swf and interact with it?

I have tried SWFLoader, but the problem is the loaded content is MovieClip and I don't know how to interact with it, and the MovieClip#numChilds is zero.

And by the way, I can't pass the flashvars to the swf.

jeudi 23 juin 2016

Pass string from php to flash

I'm just trying out PHP and AS3 in Flash CS6. I want a few strings to be passed from PHP to Actionscript3 and store them in an array. Is this possible?

Currently I'm doing this. My PHP code is

<?php
    echo "one,two,three,four";
?>

and AS3 code is:

var myRequest:URLRequest = new URLRequest("please7.php");
var myLoader:URLLoader = new URLLoader();           
myLoader.load(myRequest);
myLoader.dataFormat = URLLoaderDataFormat.TEXT;
myLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(event:Event):void {
    var variables:String = event.target.data;
    trace(variables);
    var arr1:Array = new Array();
    arr1 = variables.split(","); 
    trace(arr1);
    }

This gives me this output:

<?php
    echo "one,two,three,four";
?>

If I use myLoader.dataFormat = URLLoaderDataFormat.VARIABLES; instead of myLoader.dataFormat = URLLoaderDataFormat.TEXT; ..I'm getting this error

Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.

I want the output to be a simple [one two three four]

What am I doing wrong?

TextConverter does not import exported TextFlow

If I import a text flow into a RichText component it does not import.

I have this RichText component:

<s:RichText id="richText59">
    <s:textFlow>
        <s:TextFlow>
            <s:p>test
            </s:p>
        </s:TextFlow>
    </s:textFlow>
</s:RichText>

If I import the TextFlow below same as in the MXML file:

<s:TextFlow xmlns:s="library://ns.adobe.com/flex/spark" >
    <s:p>test
    </s:p>
</s:TextFlow>

I get a null textFlow. If I look at the parser errors vector there is an error, "Unknown namespace".

If I change the namespace to flow then then it works. I found this code that is canceling it in TextLayoutImporter.as when calling the checkNamespace() method:

/**  @private */
override protected function parseContent(rootStory:XML):TextFlow
{
    // Capture all the top-level tags of interest that can be "bound"
    // We have to do this because the attributes are applied at the point
    // of calling something like:
    // span.charAttrs = characterAttrs;
    // At one time, we just set the variable to the parameter (in the setter),
    // but now we're copying the data into a new object. This change does
    // not allow for us to parse the bindings in any order. Hence, we
    // will process the potential bindings objects first, then the
    // TextFlow objects.
    //
    // Also note the use of "..*" below. We are using this to traverse the
    // XML structure looking for particular tags and at the same time allow for
    // any namespace. So, you might see something like <flow:TextContainer> or
    // <TextContainer> and this code will capture both cases.

    var rootName:String = rootStory.name().localName;
    var textFlowElement:XML = rootName == "TextFlow" ? rootStory : rootStory..*::TextFlow[0];
    if (!textFlowElement)
    {
        reportError(GlobalSettings.resourceStringFunction("missingTextFlow")); 
        return null;
    }
    if (!checkNamespace(textFlowElement))
        return null;

    return parseTextFlow(this, textFlowElement);
}

protected function checkNamespace(xmlToParse:XML):Boolean
{
    var elementNS:Namespace = xmlToParse.namespace();
    if (!_textFlowNamespace) // Not set yet; must be parsing the TextFlow element
    {
        // TextFlow element: allow only empty namespace and flow namespace
        if (elementNS != ns) 
        {
            reportError(GlobalSettings.resourceStringFunction("unexpectedNamespace", [elementNS.toString()]));
            return false;
        }
        _textFlowNamespace = elementNS;
    }
    // Other elements: must match the namespace of the TextFlow element
    // Specifically, can't be empty unless the TextFlow element's namespace is also empty 
    else if (elementNS != _textFlowNamespace) 
    {
        reportError(GlobalSettings.resourceStringFunction("unexpectedNamespace", [elementNS.toString()]));
        return false;
    }

    return true;
}

Type #1009 Error in actionscript 3, Timer

I'm getting an error in actionscript 3 and it's something to do with my Timer. Here is the Error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at RECOVER_pacmangame_fla::MainTimeline/doCheck()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

My code involving the Timer is as follows:

var pelletcount:int
pelletcount == 0

/*Code that checks pellet collision, if collision is true,
pellets become invisible.*/

my_mc.addEventListener( Event.ENTER_FRAME, handleCollision)
function handleCollision(e:Event):void
{ 
 if (m_pel0.hitTestPoint (my_mc.x, my_mc.y, false)) 
    {m_pel0.visible = false, pelletcount = 1;} 
else 
    {;} 
}

var checkTimer2:Timer = new Timer(20);
checkTimer2.addEventListener(TimerEvent.TIMER, pelletCheck);
checkTimer2.start();

function pelletCheck(e:Event):void {
    if(pelletcount == 1){

        gotoAndStop(42);
    }

}

Sound synthesis: interpolate betweeen frequencies using AS3

I'm a little lost and hopefully someone can shed some light on this. Out of curiosity I'm working on a simple softsynth/sequencer. Some ideas were taken from the .mod format popular in the golden era of home computers. At the moment it's just a mock-up. Notes are read out from an array holding up to 64 values, where each position in the array corresponds to a sixteenth note. So far so good, everything's working as it should and the melody plays just fine. The problem arises if there's a transition from one note to another. e.g. f4 -> g#4. Since this is an abrupt change there's a noticeable pop/click sound. To compensate I'm trying to interpolate between different frequencies and started to code a simple example to illustrate my idea and verify it's working.

import flash.display.Sprite;
import flash.events.Event;
import flash.display.Bitmap;
import flash.display.BitmapData;

public class Main extends Sprite
{
    private var sampleRate:int = 44100;
    private var oldFreq:Number = 349.1941058508811;
    private var newFreq:Number = 349.1941058508811;
    private var volume:Number = 15;
    private var position:int = 0;
    private var bmp:Bitmap = new Bitmap();
    private var bmpData:BitmapData = new BitmapData(400, 100, false, 0x000000);
    private var col:uint = 0xff0000;

    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);
        bmp.bitmapData = bmpData;
        addChild(bmp);

        for (var a:int = 0; a < 280; a++)
        {
            if (a == 140)
            {
                col = 0x00ff00;
                newFreq = 415.26411519488113;
            }
            if (a == 180)
            {
                col = 0x0000ff;
            }
            oldFreq = oldFreq * 0.9 + newFreq * 0.1;
            bmpData.setPixel(position, Math.sin((position) * Math.PI * 2 / sampleRate * oldFreq * 2) * volume + bmpData.height/2, col);
            position++;
        }
    }
}

This will generate the following output: interpolated

The blue dots represent a sine wave at 349.1941058508811 hz, the red 415.26411519488113 hz and the green dots the interpolation. For my eyes, it looks like this should work! If I apply this technique to my project however, the result isn't the same! In fact, if I render the output to a wave file, the transition between those two frequencies looks like this: Goldwave screenshot

Obviously it makes the popping even worse. What could possibly be wrong? Here's my (shortened )code:

import flash.display.*;
import flash.events.Event;
import flash.events.*;
import flash.utils.ByteArray;
import flash.media.*;
import flash.utils.getTimer;

public class Main extends Sprite
{
    private var sampleRate:int = 44100;
    private var bufferSize:int = 8192;
    private var bpm:int = 125;
    private var numberOfRows:int = 64;
    private var currentRow:int = 0;
    private var quarterNoteLength:Number;
    private var sixteenthNoteLength:Number;
    private var numOctaves:int = 8;
    private var patterns:Array = new Array();
    private var currentPattern:int;
    private var songOrder:Array = new Array();
    private var notes:Array = new Array("c-", "c#", "d-", "d#", "e-", "f-", "f#", "g-", "g#", "a-", "a#", "b-");
    private var frequencies:Array = new Array();
    private var samplePosition:Number = 0;
    private var position:int = 0;
    private var channel1:Object = new Object();

    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);
        quarterNoteLength = sampleRate * 60 / bpm;
        sixteenthNoteLength = quarterNoteLength / 2 / 2;
        for (var a:int = 0; a < numOctaves; a++)
        {
            for (var b:int = 0; b < notes.length; b++)
            {
                frequencies.push(new Array(notes[b % notes.length] + a, 16.35 * Math.pow(2, frequencies.length / 12)));
            }
        }
        patterns.push(new Array("f-4", "", "", "", "g#4", "", "", "f-4", "", "f-4", "a#4", "", "f-4", "", "d#4", "", "f-4", "", "", "", "c-5", "", "", "f-4", "", "f-4", "c#5", "", "c-5", "", "g#4", "", "f-4", "", "c-5", "", "f-5", "", "f-4", "d#4", "", "d#4", "c-4", "", "g-4", "", "f-4", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""));
        songOrder = new Array(0, 0);
        currentRow = 0;
        currentPattern = 0;
        channel1.volume = .05;
        channel1.waveform = "sine";
        channel1.frequency = [0];
        channel1.oldFrequency = [0,0,0,0];
        channel1.noteTriggered = false;

        updateRow();
        var sound:Sound = new Sound();
        sound.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
        sound.play();
    }

    private function updateRow():void
    {
        var tempNote:String = patterns[songOrder[currentPattern]][currentRow];
        if (tempNote != "")
        {
            channel1.frequency = new Array();
            if (tempNote.indexOf("|") == -1)
            {
                channel1.frequency.push(findFrequency(tempNote));
            }

            channel1.noteTriggered = true;
        }

    }

    private function onSampleData(event:SampleDataEvent):void
    {
        var sampleData:Number;
        for (var i:int = 0; i < bufferSize; i++)
        {
            if (++samplePosition == sixteenthNoteLength)
            {
                if (++currentRow == numberOfRows)
                {
                    currentRow = 0;
                    if (++currentPattern == songOrder.length)
                    {
                        currentPattern = 0;
                    }
                }
                updateRow();
                samplePosition = 0;
            }


            for (var a:int = 0; a < (channel1.frequency).length; a++ )
            {
                channel1.oldFrequency[a] = channel1.oldFrequency[a]*0.9+channel1.frequency[a]*0.1;          
            }

            if ((channel1.frequency).length == 1)
            {
                sampleData = generate(channel1.waveform, position, channel1.oldFrequency[0], channel1.volume);
            }
            else
            {
                sampleData = generate(channel1.waveform, position, channel1.oldFrequency[0], channel1.volume);
                sampleData += generate(channel1.waveform, position, channel1.oldFrequency[1], channel1.volume);
            }

            event.data.writeFloat(sampleData);
            event.data.writeFloat(sampleData);

            position++;
        }
    }

    private function generate(waveForm:String, pos:Number, frequency:Number, volume:Number):Number
    {
        var retVal:Number
        switch (waveForm)
        {
            case "square": 
                retVal = Math.sin((pos) * 2 * Math.PI / sampleRate * frequency) > 0 ? volume : -volume;
                break;
            case "sine": 
                retVal = Math.sin((pos) * Math.PI * 2 / sampleRate * frequency * 2) * volume;
                break;
            case "sawtooth": 
                retVal = (2 * (pos % (sampleRate / frequency)) / (sampleRate / frequency) - 1) * volume;
                break;
        }
        return retVal;
    }

    private function findFrequency(inpNote:String):Number
    {
        var retVal:Number;
        for (var a:int = 0; a < frequencies.length; a++)
        {
            if (frequencies[a][0] == inpNote)
            {
                retVal = frequencies[a][1];
                break;
            }
        }
        return retVal;
    }
}

Thanks! =)

Actionscript 3.0 random teleportation

I'm using Flash and decided to make my animation into a game of a sort. So I started out coding and I'm pretty far into it. But I came across a small problem when I went pressed my chosen key and it did what i wanted, but randomly teleported to the characters original location.

//FRAME 1
stop();
//--Developer William Richmond

import flash.events.KeyboardEvent;
import flash.events.TimerEvent;

stage.addEventListener(KeyboardEvent.KEY_UP,moveClipdown);
stage.addEventListener(KeyboardEvent.KEY_DOWN,moveClipup);
stage.addEventListener(KeyboardEvent.KEY_DOWN,moveClipright);
stage.addEventListener(KeyboardEvent.KEY_DOWN,moveClipleft);


//Attempting the border restriction code
function limitStageBorder(object:MovieClip) {
//1.
var objectHalfWidth:uint=object.width/2;
var objectHalfHeight:uint=object.height/2;

//2.
if (object.x+objectHalfWidth>stage.stageWidth) {
   object.x=stage.stageWidth-objectHalfWidth;
}
else if (object.x -  objectHalfWidth <0) {        
   object.x=0+objectHalfWidth;    
}     

//3.    
if (object.y-objectHalfHeight<0) {        
   object.y=0+objectHalfHeight;    
}    
else if (object.y + objectHalfHeight > stage.stageHeight) {
   object.y=stage.stageHeight-objectHalfHeight;
}
}
//down
function moveClipdown(event:KeyboardEvent):void
              {
                  if(event.keyCode == 83)
                  {
                      mcSquare1.y += 25
                  }
              }
//up
function moveClipup(event:KeyboardEvent):void
              {
                  if(event.keyCode == 32)
                  {
                      mcSquare1.y -= 10
                      mcSquare1.gotoAndPlay(20);
                  }
              }
            //right  
function moveClipright(event:KeyboardEvent):void{
                  if(event.keyCode == 68){
                      trace("I am running to the right");
                      mcSquare1.scaleX = 0.75;
                      mcSquare1.x += 20
                      gotoAndStop(10);
                  }
}

            //Left  
function moveClipleft(event:KeyboardEvent):void{
                  if(event.keyCode == 65)
                  {
                      trace("I am running to the left");
                      mcSquare1.scaleX = -0.75;
                      mcSquare1.x -= 20
                      gotoAndStop(10);
                  }
              }

FRAME 10

stop();
//--Developer William Richmond

import flash.events.KeyboardEvent;
import flash.events.TimerEvent;

stage.addEventListener(KeyboardEvent.KEY_UP,moveClipright10);
stage.addEventListener(KeyboardEvent.KEY_UP,moveClipleft10);

            //right  
function moveClipright10(event:KeyboardEvent):void{
                  if(event.keyCode != 68){
                      trace("I am standing");
                      mcSquare1.scaleX = 0.75;
                      mcSquare1.x += 20
                      gotoAndStop(1);
                  }
}

            //Left  
function moveClipleft10(event:KeyboardEvent):void{
                  if(event.keyCode != 65)
                  {
                      trace("I am standing");
                      mcSquare1.scaleX = -0.75;
                      mcSquare1.x -= 20
                      gotoAndStop(1);
                  }
              }

So if anyone could have a go at helping out, it would be highly appreciated!

Actionscript 3: Buttons always on top?

I'm working on a little game. So I need 4 layers in my main-timeline. In the bottom layer is a movieclip with some buttons in them. In the two layers above there are also movieclips for effects and actions and the layer on the top is for actionscript. The sequence for the layers is intended.

And when I test it I can't click on any buttons, because for sure there are movieclips above them. Is there a possibility in actionscript to say, that all buttons are always on top?

AS3 Wheel of Fortune spinning

I'm working on wheel of fortune project but i'm currently struggling with the code. I have attached the design of the wheel. I'm not a coder, i'm a designer and i need to do all the animation and the effects but i want to do it professional and that part is very important. What i want to do is when you click on the spin button the wheel to rotate for 4-5 seconds with ease in/out effect and to stop each time on different random sector. Ill do different animations for each sector in separate movie clip and when it stops on a sector i want the movie clip related with that sector to start playing. My idea is to make the wheel as a movie clip and each sector animation movie clips to be nested in it so when it stops that specific movie clip starts. Maybe I need to make each position of the wheel on key frame and to place the animations on these frames, but not sure if that is the right way. One of the thing is that these movie clips with the effects shoud be easy for re position. I need to move them on the stage if needed and that's why i don't want them to be triggered with code. If you can guide me step by step how to do that part i will appreciate your help. Thanks in advanced. wheel design

mercredi 22 juin 2016

AS3 Air for Android filepath

Hello and thank you in advance for any help...

I have the following function that should display all the images in a sub-folder of the app storage directory:

public function mygallery():void
{
        var gallery:File = File.applicationStorageDirectory.resolvePath("IMAGES/");
        var gfiles:Array = gallery.getDirectoryListing();

        var gcount:int = 0;
        gcount = gfiles.length;

        var x_counter:Number = 0;
        var y_counter:Number = 0;

        createContainer();
        callThumbs();

        function createContainer():void
        {
            container_mc = new MovieClip();
            container_mc.x = gx;
            container_mc.y = gy;
            //container_mc.width = gthumbw;
            //container_mc.height = gthumbh;
            addChild(container_mc);
        }

        function callThumbs():void
        {
            for (var j:uint = 0; j < gcount; j++)
            {
                var thumb_url = gfiles[j].nativePath;
                var thumb_loader = new Loader();
                thumb_loader.load(new URLRequest(thumb_url));
                thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);

                thumb_loader.x = (gthumbw+gspw)*x_counter;
                thumb_loader.y = (gthumbh+gsph)*y_counter;
                if (x_counter+1 < gcol)
                {
                    x_counter++;
                }else
                {
                    x_counter = 0;
                    y_counter++;
                }
                //trace(gfiles[j].nativePath);
            }
        }

        function thumbLoaded(e:Event):void
        {
            var my_thumb:Loader = Loader(e.target.loader);

            my_thumb.width = gthumbw;
            my_thumb.height = gthumbh;

            container_mc.addChild(my_thumb);
        }
}

the gcount returns the correct number of files in the folder but for some reason the images do not display at all.

When I run this in windows it works fine, which leads me to believe that it's either a sandbox issue for Android or I'm using the file paths incorrectly.

Any advice is greatly appreciated

MOUSE_DOWN not firing when expected - AS3, Actionscript

MOUSE_DOWN not firing when expected - AS3, Actionscript

I am not seeing the below code trace in MOUSE_DOWN fired, until I lift the mouse button back up.

This happens even on a new FLA, with only MOUSE_DOWN, MOUSE_UP and CLICK handler code -- nothing else.

Regardless of what I do, I only see MOUSE_DOWN, MOUSE_UP and CLICK traced out AFTER I lift (release) the mouse button.. See code below.

It happens if I attach the handlers to the stage; or to a sprite.

It happens with/without buttonMode being set.

It happens with/without preventDefault() being called in CLICK..

It happens using event:MouseEvewnt or event:Event as some have suggested.

When I click, I see nothing. When I release, I see this: Mouse down Mouse up Mouse CLICK

Why don't I see "Mouse down" when clicking (before releasing)?

What the heck am I missing here?

Thank you!

stage.addEventListener(MouseEvent.MOUSE_DOWN, function(event:MouseEvent)
             {
                // event.preventDefault();  
                 trace("Mouse down");   
             } );

 stage.addEventListener(MouseEvent.MOUSE_UP, function(event:MouseEvent)
            {
                // event.preventDefault();
                trace("Mouse up");
            } );

 stage.addEventListener(MouseEvent.CLICK, function(event:Event)
        {
            // event.preventDefault();
            trace("Mouse CLICK");

        } );

ActionScript 3 move an object in local space relative to global space

I'm trying to do some 3D transforms with AS3 and I've run into a problem where I'm not sure how to make this work.

I have a list of boxes within a movieclip, where this movieclip is rotated slightly. Something like this (values are made up, just for illustration):

Initial State

Now what I would like to do is take one of the boxes from inside this group and move it to a position in the global space. Like so:

Intended result

How would I do this with ActionScript 3?

Trying to compile old adobe flex project with Intellij. Unresolved variables, funtions, etc. Is there an easy fix to fix these errors?

So I've done research on if apache flex can be ran throught the IDE intellij. Most of the info says it can be. But when I created my project, I created it through adobe flex a year ago or two. I'm wanting to change my IDE from FlashBuilder to Intellij.

I've opened my project into IntelliJ, and it looks correct except I've gotten multiple errors saying Unresolved variable, unresolved type, unresolved function, etc.

My Questions:

  1. Will these errors prevent my program from building?

  2. Is there an easy fix for these errors?

Clone object when dragging

I am trying to clone my object when dragging (the object is called pink_key).

Unfortunately, when dragging, the object is not cloned.

import flash.events.MouseEvent;

this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging, true);
this.addEventListener(MouseEvent.MOUSE_UP, stopDragging, true);

function startDragging(e:MouseEvent) {

    var clone_pink_key:MovieClip = new MovieClip();
    clone_pink_key.graphics.copyFrom(pink_key.graphics);

    addChild(clone_pink_key);
    clone_pink_key.x=60;

    pink_key.startDrag();


}

function stopDragging(e:MouseEvent) {
    pink_key.stopDrag();
}

Any help appreciated!

As3 Workers Passing custom Objects

Making a worker that renders a mesh from away3d and sends it over to the display. I went ahead and registered all the classes so my "WorldRender" worker could pass a mesh in AMF format to my main swf and add it on stage. Think of my worker as someone that keeps track of all the parts of my world from a storage area and parses them properly.

I'm able to create a worker just fine. Waiting until the worker is ready to handle commands and everything. Ran into a few errors before where it didn't know what a Mesh or a Sector was but now all of the primary classes are registered.

Yet.

Yet..

enter image description here

Here I am registering both MaterialBase and BounidngVolumeBase and my worker thread is still throwing the same type errors it did when I didn't register my other classes.

TypeError: Error #1034: Type Coercion failed: cannot convert Object@75fe569 to away3d.materials.MaterialBase.
TypeError: Error #1034: Type Coercion failed: cannot convert Object@75f8df1 to away3d.bounds.BoundingVolumeBase.

I don't want to have to go and use a class made of primitives like a custom Cube class and then render the mesh on my main thread because of the way my engine works. . . I'm already indexing the meshes to be able to remove easily by matching them with other values in a dimensional vector. (Actually on second thought I'm not sure which would use more memory matching child index with a Cube class in both the main and worker thread or storing a collection of meshes for ease of access in my worker thread...Okay, maybe the first one, but I really want to know why this isn't working at this time for the sake of speed)

Either way, any help on this would be appreciated as my energy from the coffie shot mix I had is starting to wear out.

Sources: WorldRender worker swf http://ift.tt/28OKiWp WorldRender class in main thread http://ift.tt/28LMAlt

RenderEngine constructor exerpt calling on my WorldRender class in my main thread ("supervisor" of WorldRender for camera movement and other future render engines)

    worldRender = new WorldRender(_viewport);

    var targetXDistance:int = _viewport.camera.x + (_viewDistance / 2);
    var targetZDistance:int = _viewport.camera.z + (_viewDistance / 2);

    for (var x:int = _viewport.camera.x - (_viewDistance / 2); x < targetXDistance; x++)
    {
        for (var z:int = _viewport.camera.z - (_viewDistance / 2); z < targetZDistance; z++)
        {
            var sectorToRender:Sector = world.getSector(x, 0, z);

            //order:RENDER , sector:SECTOR, combine:BOOLEAN
            var order:Object = new Object();
            order.order = WorldRender.RENDER;
            order.sector = sectorToRender;
            order.combine = true;

            worldRender.issueOrder(order);

        }
    }

create a login page with email and password in javascript

i want to create a login page.in that i want few things that if i enter wrong email address than it will give alert and if left blank then it will give alert and also for inappropriate email address and in the case of password it will show the same`. here i used userid so please change that to email address

<html>
<head>
    <script language="javascript">
        function check(form) {
            if(form.userid.value == "id@gmail.com") {
                alert("correct username")
            } else if (form.userid.value == "") {
                alert ("blank username")
                                
            } else if(form.pswrd.value == "123") {
                alert("correct details")
            } else if(form.pswrd.value == "") {
                alert ("blank password")
            }
        }
    </script>

</head>
<body>
<h1>Login </h1>
<form name="login">
    Username<input type="text" name="userid"/>
    Password<input type="password" name="pswrd"/>
    <input type="button" onclick="check(this.form)" value="Login"/>
    <input type="reset" value="reset"/>
</form>

</body>
</html>

mardi 21 juin 2016

How to give differents directions of bullets on one array?

im very new on javascript, i was doing a ship gaming that you have to kill some asteroids, and when you take some differents of "objects" on the screen we expand our number of bullets. Okey, going to the point i could get 3 bullets on the screen when you take diffirents objects, but now i want to give 2 of that 3 bullets of the array different directions. When i tried, i have the problem that i give the 3 bullets the same direction, i know why but im for at least 5hrs trying to fix this and i cant.

Im programming on Flash Builder 4.7 with different classes, i ll give the code of the array who is in the main, and the bullet class so as the hero class too.

Main Array

public function evUpdateBullet():void//here execute update of my class Bullets
    {
        var i:int;
        for(i=myBullets.length-1; i >= 0; i--)
        {
            if(myBullets != null) //to be ?
            {
                if(myBullets[i].isDestroyed) //is destroyed Bullets?
                {
                    myBullets[i] = null;
                    myBullets.splice(i, 1); //deleted elements.
                }else
                {

                    myBullets[i].evUpdate();





                }
            }
        }
    }

here i push the array and create the bullet, remember myBullets is the name of the array.

public function evShoot(posX:int, posY:int):void//here create the bullet and push in the array
    {
        attack1 = new Bullet;
        attack1.Spawn(posX, posY);
        myBullets.push(attack1);

}

here i show the Hero code, where i define the position of the bullet is going to spawn on the screen.

if (isPressing_Shoot && !isDestroyed)// Here execute the event shoot without power
        {
            Main.instace.evShoot(model.x, model.y);


            isPressing_Shoot = false;
            canShoot = false;

        }


        evDestroyed();
    }

here is the code from Bullet class

first the spawn

public function Spawn(posX:int, posY:int):void
    {
        isDestroyed = false;//first parameter of my bullet

        model = new MCbullet;
        Main.layer1.addChild(model);//painting the hero in the stage
        model.x = posX;//position in the stage wiht the hero
        model.y = posY;
        model.tigger.visible = false;

    }

then the Update

public function evUpdate():void//here conect with update general
    {
        if (model != null)//to be?
        {

            model.y -= 12;//move of my bullet
            //model.x -= 12;





            if (model.y <= 0 )
            {
                evDestroyed();
            }
        }

    }

in this update i set the movement of y, so i can shoot vertically, but.. when i try to add an x.move, i do for the all array, so i want to know how i can give different move, for differents bullets of the same array.

Flash not reporting runtime errors any more. Did I turn something off?

I've apparently turned something off? Even when I write really bad code (like trying to call a function that isn't there or divide an integer into a fraction), the flash player boots, shows a background color and stops there. No messages in the output window or compiler errors window. If I fix my code, it all runs fine, but for about 30 minutes (ever since I started trying to work with bitmaps for a sprite sheet) I get no runtime errors no matter what kind of mistake I type in my code. Anyone know how to turn it back on?

I've checked my actionscript settings and I have both warning mode and strict mode checked on.

How can I pass ComboBox labels in AS3 to jsfl file?

I'm creating a swf panel called "CAD-Standard Panel" in Adobe Animate which has a combo box and simply i need to pass its label"exeType " to a variables in a jsfl file "DB1".

AS3 code

var exeType = drop_box_1.selectedItem.label;
Demo_mc.addEventListener(MouseEvent.CLICK, test1);
function test1(e:MouseEvent):void {     
MMExecute("fl.runScript(fl.configURI + 'WindowSWF/Script-1.jsfl')");
}

JSFL code

var swfpanel = fl.configURI + 'WindowSWF/CAD-Standard Panel.swf';
var DB1 = swfpanel.getControlItemElement("drop_box_1");
alert (DB1);

So I face an error that "swfpanel.getControlItemElement" is not a function but i need to establish a connection to pass this variable.

Any suggestions

Save data in dynamical text in another frame while working on current frame as3

I am working on Flash actionscript 3 to create a quiz using combobox. I used the following code.

stop();
box1.addEventListener(Event.CHANGE, changeHandler);
\\box1 is combobox 1

function changeHandler(event:Event):void

{

if (box1.selectedIndex == 1)
\\there are two values in combobox with index 1 and 2

{
    name1.text = "1) Wrong";
\\name1 is the dynamical text box
}
else if (box1.selectedIndex == 2)
{
    name1.text = "1) Right";
}
else
{
    name1.text = "";
}
}

I put the dynamical text box on frame 4 while the combobox is in frame 2 I created two comboboxes. when I select an option from combobox 1, I get an error like this: Error #1009: Cannot access a property or method of a null object reference.

So I extended the dynamical text layer from frame 2 to frame 4. But after running the program, the result is shown only in frame 2 immediately after selecting the value from combobox 1; so that the result is displayed before selecting combobox 2.

What I need is to save the result in frame 4 and it is displayed only when I go to that frame using next buttons.

Any help would be appreciated. I am beginner in Flash actionscript.(I prefer using interface than coding).

lundi 20 juin 2016

AS3 event listeners inside loop

I'm having a bit of a hard time figuring this one out.

I'm creating an Air/Flash app that uploads files from a local directory to the server.(without user interaction). I'm creating an Array of the files found in the folder and can upload them fine without any issues. However, I can not keep track of the event listeners; meaning, the for loop obviously completes before the event listeners for each upload.

Is there a way to keep track of the event listeners and find out when the last one finished?

Any help is greatly appreciated...

Here's my code:

public var UPLOAD_URL:String = "http://myhost/dev/uptest.php";
upbtn.addEventListener(MouseEvent.CLICK, uploadme);
public function uploadme(event:MouseEvent):void
    {
        preloader.visible = true;
        var desktop:File = File.applicationStorageDirectory.resolvePath("photo");
        var files:Array = desktop.getDirectoryListing();
        for (var i:uint = 0; i < files.length; i++)
        {
            var date:Date = new Date(); // get new date
            var mytime:Number = Math.round(date.valueOf()/1000);
            var ur:URLRequest = new URLRequest();
            var uv:URLVariables = new URLVariables();
            uv.filename = files[i].name;
            ur.data = uv;
            ur.method = URLRequestMethod.POST;
            ur.url = UPLOAD_URL;

            files[i].addEventListener(ProgressEvent.PROGRESS, updateProgress);
            files[i].addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, doneUpload);
            files[i].addEventListener(IOErrorEvent.IO_ERROR, fileError);
            files[i].upload(ur);
            //trace(i)

            function updateProgress(event:ProgressEvent):void
            {
                //wait preloader.visible = true;
                //trace(event.currentTarget.name);
            }
            function doneUpload(event:DataEvent):void
            {
                //var loader2: URLLoader = URLLoader(event.target);
                //trace(i);

                trace(event.data);
                //preloader.visible = false;
            }

            function fileError(event:IOErrorEvent):void
            {
                trace("error");
            }               
        }
    }

How swf files imports other packages?

I am trying to analyze a swf file but I am completely lost since I don't know flash,actionscript or anything related to it. I decompiled the swf file to find URL endpoints which I will later use in the pentest but I couldn't find any. Although, I am sure there are some URLs hidden in the decompiled code because when I click buttons in the original swf file, it sends XHR requests to different endpoints. So there must be something I am missing. I find the code below interesting:

import com.pentest.community.dto.*;
import com.pentest.internal.login.dto.*;
import com.pentest.rest.internallogin.*;

public static function init(_arg1:IFlexModuleFactory):void{
try {
     if (getClassByAlias("com.pentest.community.amf.dto.profile.avatar.AvatarDto") == null){
                registerClassAlias("com.pentest.community.amf.dto.profile.avatar.AvatarDto", AvatarDto);
     };
     } catch(e:Error) {
            registerClassAlias("com.pentest.community.amf.dto.profile.avatar.AvatarDto", AvatarDto);
        };
  }

I understood that my precious URL endpoints are in the imported packages. But I don't know how to download them. This doesn't even seems possible since how does my browser know where the "com.pentest.internal.login.dto" is? Can you explain me how importing works in the swf file?

Sorry if this question doesn't make sense or doesn't fit to stackoverflow.

AS3 Editing event.target after being clicked befor executing gotoAndPlay("abc");

Greetings stackoverflow members,

i have 3 animated movieclips nested in a movieclip. What I'm trying to do is to get the name of the instance clicked and edit it befor applying gotoAndPlay. I can get the name but when ever I try to edit it I'm getting the Error:

Symbol 'Buttons MC', Layer 'Actions', Frame 1, Line 30 1061: Call to a possibly undefined method gotoAndPlay through a reference with static type String.

Here's my code so far:

   [Bindable] var targetName:String;

var _userInput:String = new String();
_userInput = targetName;

//array for buttons
var btnArray:Array = [INS_Btn1, INS_Btn2, INS_Btn3];

//add eventlistiners
for(var i:uint=0; i<btnArray.length; i++) {
    btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
    btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
    btnArray[i].addEventListener(MouseEvent.CLICK, bClick);
    btnArray[i].buttonMode=true;
}

//btn over state
function bRollover(event:MouseEvent):void{
    event.target.gotoAndPlay("Over");
}
//btn out state
function bOut(event:MouseEvent):void{
    event.target.gotoAndPlay("Out");
}
//btn click state
function bClick(event:MouseEvent):void{
    targetName = event.target +("_ani")
    targetName.gotoAndPlay("Active");
}

What I want is that the MC clicked should go and play the animation of an onther MC. Best I should mention that I'm a beginner in AS3.

dimanche 19 juin 2016

MovieClip Undefined?

I am trying to make a program where I can press a button to make a timer animation start. However whenever I add a try to add a MovieCLip to the stage it always says: Undefined... Why. Someone help me :(.

Here is my code:

var mc_hero:MovieClip = new hero_mc;
addChild(hero_mc);



var rectangle:Shape = new Shape; 
rectangle.graphics.beginFill(0xFF0000);
rectangle.graphics.drawRect(100, 100, 25,25); 
addChild(rectangle);

var circle:Shape = new Shape;
circle.graphics.beginFill(0x99ff00);
circle.graphics.drawCircle(90, 90, 25);
addChild(circle);


var moveleftTimer: Timer = new Timer(2000,10);
moveleftTimer.start();
moveleftTimer.addEventListener(TimerEvent.TIMER,moveleft);

function moveleft(event:TimerEvent):void 
{

}

samedi 18 juin 2016

How to pause and restart a NetStream object?

I have a NetStream object, based upon the following code:

streamID = "mystreamkey";
videoURL = "rtmp://mystreamurl";

vid = new Video();

nc = new NetConnection();

nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void{}, streamConnected: streamConnected, streamDisconnected: streamDisconnected };
nc.connect(videoURL);

...

metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;

netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
addChild(vid);

All this is working fine, and I can also use netStreamObj.pause() to pause the live stream.

But how do I restart it? netStreamObj.play() won't work - it requires one parameter, so then I wrote this:

netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);

But this isn't working either.

How do I restart the stream, so that it connects to the live stream it was previously connected to?

vendredi 17 juin 2016

AS3 Flv Cuepoint

I am working on a project currently and I would like to inject ActionScript CuePoints into an input video file.

I cannot find relevant documentation for addASCuePoint. I know the time parameter is seconds, but can't find the correct formula.

My video file is 25fps, so how do I add a cue point for 00:01:10:23 (minute 1, 10 seconds and frame 23) in seconds? Also, the main project, runs at 25 fps.

Thanks

ActionScript: Intersection multiple objects while not intersecting any?

I have been working on a hit detection algorithm for a while, where I have a series of squares which are in an array (blocks), and through a loop, the array is gone through and it is checked if an item (bus) is intersecting it.

The original code goes as follows:

// Gets important variables from controller class
var blocks:Array = main.blocks;
var map:Map = main.game.gameMap;
var game:GameMapScreen = main.game;
var busSpeed:uint = 5;

// Centers the 'map' around the 'bus'
game.x = (bus.x) * -1  + stage.stageWidth / 2;
game.y = (bus.y) * -1 + stage.stageHeight / 2;
map.setChildIndex(bus, map.numChildren - 1);

// Creates the new x and y values for where the bus will move
var angle:Number = (bus.rotation / 360) * (Math.PI * 2);
var dx:Number = Math.cos(angle);
var dy:Number = Math.sin(angle);
var newX:Number = dx * busSpeed;
var newY:Number = dy * busSpeed;

// Gets a clone of rectangle around bus, moves it to new x and y
busRect.x += newX;
busRect.y += newY;

And then it goes through the blocks array and tests the bus rectangle again each block's rectangle

var hitting:Boolean = false;
for(var i:uint = 0; i < blocks.length; i++)
{
   if(busRect.intersections(blocks[i].getRect(map))
   {
      hitting = true;
      break;
   }
}

And then it checks to see if hitting, then moves if not

if(hitting)
{
   bus.x = newX;
   bus.y = newY;
}

The problem I discovered was that when the bus is not intersecting a block, it appears to be "intersecting" two blocks.

The blocks are arranged in a grid-like fashion, with spaces in between where it should not be intersecting... but it appears to be intersection two, and only one when actually inserting a block.

After checking many times and consulting with others, we cannot figure out the problem. Why is it that when we arrange the blocks in a grid like fashion, stick then in an array, and checks if it is hitting something, it intersection 2 blocks if not actually intersecting, and intersection 1 if it is...

Any ideas?

Flash AS3 ReferenceError: Error #1056: Cannot create property

I am following a tutorial on making a rhythm game in Flash, and am new to AS3. I keep getting this error:

ReferenceError: Error #1056: Cannot create property destroy on flash.display.Shape.
at source_fla::MainTimeline/removeButtons()[source_fla.MainTimeline::frame5:27]
at btnSongSelect/clickThis()[btnSongSelect::frame1:25]

referring to the following code:

//this function will remove all of the buttons from the stage
function removeButtons():void{
    //we're going to use the same loop
    for(var i:int=0;i<numChildren;i++){
        var remove = getChildAt(i);
        //set the target's destroy variable to true
        remove.destroy = true;
    }
}

Can someone please explain to me the cause of the error and a possible fix? Thank you.

How to run a method when onPublish is triggered in Adobe Media Server?

I have the following code inside Adobe Media Server's main.asc (latest version, 5.0.10 I think):

application.onPublish = function (clientObj, streamObj) {
  for (var i = 0; i < application.clients.length; i++){
    application.clients[i].call("streamConnected");
  }
}

And this code inside my ActionScript (3.0) file, connected to my flash file:

nc = new NetConnection();

nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void{}, streamConnected: function():void{} };
nc.connect(videoURL);

...

public function streamConnected(...rest):void {
  trace("Stream Connected");
}

I'm not too sure what my code means - most of it has been sourced from various sections of the Internet, so any help would be greatly appreciated.

FileSystemList sorting by date

I've got this FileSystemList that, obviously, list files from a specified directory. All works great except that I want to sort the listing based on created date for the files.

Is this possible for a FileSystemList ?

Thanx!

Changing world's in flashpunk

I'm trying to make my first actual game in AS3, for this I am using flashpunk due to it's simplicity.

I have got to the point where I have a moving character and a textbox when I go infront of a door.

When I am infront of a door, two variables are changed inside the player class:

public var onDoor:Boolean = false;
public var doorType:String = ""

You can probably guess what onDoor does, doorType is the name the class. It's set like this:

    public static var BedroomDoor:Door = new Door(350, 331, "ApartmentBedroom")

ApartmenBedroom being the name of the world the door leads to.

Inside the main class where flashpunk is initialised, I have this function:

    public static function ChangeLevel(world:String)
    { 
        var newWorld = getDefinitionByName(world) as Class
        FP.world = new newWorld
    }

But when I go to the door and press X infront of the door which calls the function, I always get this error:

[Fault] exception, information=ReferenceError: Error #1065: Variable ApartmentBedroom is not defined.

Can anyone help fix this?

as3 error: ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value

I am following a tutorial on building a rhythm game in as3 here, and I am very new to the language. On running the swf, I get the following error in the output:

ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value.
at source_fla::MainTimeline/makeLvl()[source_fla.MainTimeline::frame10:116]

I have tried some previous solutions posted to the same error, but I have not been able to resolve the issue.

Here is the source code:

stop();
stage.focus = stage;
//VARIABLES
//sTime is the current frame that is being played
//Once it reaches sTempo, then it will be reset
//and a note will be created
var sTime:int = 0;
//sTempo is how many frames it takes before
//a note is created. Because it's 12, and
//the frame rate is 24, it will take a half of a second
//for a note to be made
var sTempo:Number = 12;
//sNote is the current arrow of the level that is created
//0 makes no arrow
//1 makes a left arrow
//2 makes an up arrow
//3 makes a down arrow
//4 makes a right arrow
var sArrow:int = 0;
//arrowSpeed is how fast the arrow moves up the screen
var arrowSpeed:Number = 10;
//gameIsOver is whether the game's over
var gameIsOver:Boolean = false;
//the score variable
var score:int = 0;
//either perfect, great, nice, or good
var scoreString:String = '';

var combo:int = 0;

var mcHealth:Number = 0;


//Booleans checking if the arrows are touching the receptor
var touchLeft:Boolean = false;
var touchUp:Boolean = false;
var touchDown:Boolean = false;
var touchRight:Boolean = false;

function beginCode():void{
    addEventListener(Event.ENTER_FRAME, makeLvl);

    //make the level array longer
    lvlArrayAll[lvlCurrent].push(0,0,0,0,0);
}

function makeLvl(e:Event):void{
    //code here will create the level
    if(sTime < sTempo){
        //if the required time hasn't reached the limit
        //then update the time
        sTime ++;
    } else {
        //if the time has reached the limit
        //then reset the time
        sTime = 0;
        //if an actual arrow can be made
        if(lvlArrayAll[lvlCurrent][sArrow] != 0){
            var currentArrow:MovieClip; //this will hold the current arrow
            if(lvlArrayAll[lvlCurrent][sArrow] == 1){
                //place a left note onto the stage
                currentArrow = new arrowLeft();
                //set the _x value of the note so that it is in the
                //right place to touch the receptor
                currentArrow.x = 105    ;
                //set the note's y coordinate off of the stage
                //so that the user can't see it when it appears
                currentArrow.y = 0;
                //setting the key that needs to be pressed
                currentArrow.keyCode = 68;
                addChild(currentArrow);//add it to stage
            } else if(lvlArrayAll[lvlCurrent][sArrow] == 2){
                //place an up note onto the stage
                currentArrow = new arrowUp();
                currentArrow.x = 230;
                currentArrow.y = 0;
                currentArrow.keyCode = 70;
                addChild(currentArrow);
            } else if(lvlArrayAll[lvlCurrent][sArrow] == 3){
                //place a down note onto the stage
                currentArrow = new arrowDown();
                currentArrow.x = 355;
                currentArrow.y = 0;
                currentArrow.keyCode = 74;
                addChild(currentArrow);
            } else if(lvlArrayAll[lvlCurrent][sArrow] == 4){
                //place a right note onto the stage
                currentArrow = new arrowRight();
                currentArrow.x = 480;
                currentArrow.y = 0;
                currentArrow.keyCode = 75;
                addChild(currentArrow);
            }
        }
        //get the next arrow if it the song isn't finished
        if(sArrow < lvlArrayAll[lvlCurrent].length){
            sArrow ++;
        } else {
            //if the song is finished, then reset the game
            gotoAndStop('win');
            gameIsOver = true;
            //then remove this enter_frame listener
            removeEventListener(Event.ENTER_FRAME, makeLvl);
        }
    }

    //checking if mcReceptor is touching any arrows
    //first we reset the variables we got last time just in case they aren't true anymore
    touchLeft = false;
    touchUp = false;
    touchDown = false;
    touchRight = false;
    //this for loop will be used for the hit testing
    for(var i:int = 0;i<numChildren;i++){
        var target:Object = getChildAt(i);
        if(target.keyCode != null && target.hitTestObject(mcReceptor)){//if the object is an arrow and the receptor is touching it
            if(target.keyCode == 68){//if left arrow
                touchLeft = true;
            } else if(target.keyCode == 70){//if up arrow
                touchUp = true;
            } else if(target.keyCode == 74){//if down arrow
                touchDown = true;
            } else if(target.keyCode == 75){//if right arrow
                touchRight = true;
            }
        }
    }
    //changing the score text
    mcTxt.txtScore.text = 'Score:  '+score;
    mcTxt.txtCombo.text = 'Combo:  '+combo;
    mcTxt.txtScoreString.text = scoreString;
}

//this function will change the health depending on how much health change
//it needs, positive or negative
function changeHealth(healthDiff:Number):void{
    healthDiff = 100;//only changes in percentages
    //checking if the health is already at it's full
    //or will be full after this hit
    if(mcHealth + healthDiff >= 100){
        mcHealth = 100;
    } else if(mcHealth + healthDiff <= 0){
        //checking if the health will be equal or below 0
        gotoAndStop('lose');
        gameIsOver = true;
        removeEventListener(Event.ENTER_FRAME, makeLvl);
    } else {
        //if there are no problems
        mcHealth += healthDiff;
    }
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeys);
function checkKeys(event:KeyboardEvent):void{
    //if the left key is down and no left arrows are touching the receptor
    if(event.keyCode == 68 && !touchLeft){ 
        changeHealth(-10);//make the health go down
        combo = 0;
        scoreString = 'Bad';
    } else if(event.keyCode == 70 && !touchUp){//and so on
        changeHealth(-10);
        combo = 0;
        scoreString = 'Bad';
    } else if(event.keyCode == 74 && !touchDown){
        changeHealth(-10);
        combo = 0;
        scoreString = 'Bad';
    } else if(event.keyCode == 75 && !touchRight){
        changeHealth(-10);
        combo = 0;
        scoreString = 'Bad';
    }
}

beginCode();

Can someone tell me why this error is occurring? Thank you.

how to load external swf file in full screen mode?

one

Blockquote

A.swf

Blockquote

and Second

Blockquote

B.swf

Blockquote

. load b.swf file in full screen mode from a.swf file

jeudi 16 juin 2016

While moving the enemy left to right, if you change levels he keeps going

public function goalieLoop(e:Event):void { if (goalie!=null) { if (direction=="right") { goalie.x+=5; }

            else
            {
                goalie.x-=5;
            }     
            if (goalie.x==500 && direction=="right")
            {
                direction="left";
            }
            else if (goalie.x==300 && direction=="left")
            {
                direction="right";
            }

        }
    }

this is how i make my enemy move left to right, but once I get to the next level, depending on the way he was going, he keeps going that direction off the screen. If anymore code is needed, please ask. Thank you.

Seekbar for mp3 player in Actionscript 3.0 Flash CS-6

I'm trying to create a music player in Flash CS6. I'm new to Flash. I have created the play/pause/volume buttons. I have also been able to extract the mp3 information using the id3 tags. So i have the song duration. I now need to create a seekbar/progress bar. I have taken the progress bar from the components, but do not understand how to code it now. Please help!

mercredi 15 juin 2016

Iterating through item variables

I'm asking a question that hasn't been answered very well (and as a result has made me post this question).

I'm trying to dynamically save objects in a game I'm making (I already have a save feature, it's just clunky and I want to make it more efficient). What this dynamic saving involves is checking if all variables of the object you're saving are currently registered using the getClassByAlias function. Here's what the first part of the code looks like:

var objectClass:* = getDefinitionByName(getQualifiedClassName(saveItem));

try {(getClassByAlias(getQualifiedClassName(saveItem)));}
catch (err:Error) {registerClassAlias(getQualifiedClassName(saveItem), objectClass);}

So what this does is it checks if the object's class is currently registered, and registers it if it isn't. Unfortunately I have many classes that contain variables of other custom classes and must also register those classes. I didn't want to manually register every single class so what I've been trying to do is iterate through all the variables of the current object and if that variable's class isn't registered it registers it and then iterates through those variable's variables and continues registering, and so on until all unregistered classes become registered. This will allow me to save literally anything I want because it'll register all the variables that aren't registered on the fly and will make things extremely easier for me.

Seemingly the only way to see an object's variables at run-time is to use the describeType function. This returns an XML instance and you can then access the variables using ..variable (this is an XMLList). This is where I get stuck. I need a way to convert this XML code back into the variable so I can access its variables to check if any of those are unregistered. Here's an example of the XML code that references a custom class variable of this custom class I'm currently iterating through:

<variable name="itemCondition" type="item::ItemCondition">
    <metadata name="__go_to_definition_help">
        <arg key="pos" value="882"/>
    </metadata>
</variable>

I need a way to convert this back into the original ItemCondition so that I can go through its variables and continue registering. This is more or less the breakdown of the code I need (and what I have so far):

private static function registerVariables(saveItem:*):void {
    var objectClass:* = getDefinitionByName(getQualifiedClassName(saveItem));

    try {(getClassByAlias(getQualifiedClassName(saveItem)));}
    catch (err:Error) {registerClassAlias(getQualifiedClassName(saveItem), objectClass);}

    for each (var variable:XML in describeType(saveItem)..variable) {
        var currentVariable:* = SaveAndLoad.xmlToObject(variable);
        var currentClass:* = getDefinitionByName(getQualifiedClassName(currentVariable));

        try {(getClassByAlias(getQualifiedClassName(currentVariable)));}
        catch (err:Error) {
            registerClassAlias(getQualifiedClassName(currentVariable), currentClass);
            SaveAndLoad.registerVariables(currentVariable);
        }
    }
}

private static function xmlToObject(variable:XML):* {
    //Code here that gives me the reference to the current variable
}

Any help would be greatly appreciated. My brother works with Java/C++ and has made something very similar to this, I was hoping there was a way in Flash.

Performance of array reverse in ActionScript 3

I have two code snippets . which one is better.

var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
texts.reverse();
for(var index:int=0; index < texts.length; index++) {
    trace(texts[index]);
}

Or

var texts:Array = new Array(1,2,3,4,5,6,7,8,9,10);
for( var index:int = texts.length; --index;) {
      trace(texts[index]);
}

In former we have reverse operation and then print it and in latter we start from the length and start printing the array. The goal is to traverse the array from last.

How to find when live RTMP stream stops in ActionScript?

I've currently got the following code, where streamVideo is an FLVPlayBack component:

streamVideo.addEventListener( VideoEvent.STATE_CHANGE, onVideoStateChange );

streamVideo.isLive = true;
streamVideo.source = "rtmp://mystreamurl";

function onVideoStateChange(evt:VideoEvent):void {
  var streamVideo:FLVPlayback = evt.target as FLVPlayback;
  switch (evt.state) {
    case VideoState.CONNECTION_ERROR:
      trace( 'Connection error' );
      break;
    default:
    trace( 'Player is: ' + evt.state );
  }
}

This gives me Player is: playing when my stream comes on, but when my stream goes off, I don't get any sort of notification.

How to remove filter button from a column in mdatagrid

This is the filter feature. http://ift.tt/25Y9YX8 I want to remove the filter icon from one of the columns since it is using itemRenderer and not filterable.

parseInt in JavaScript or AS3 returning wrong value

Can someone please explain why all these parseInt operations evaluate to the same number 10153593963283296?

parseInt('10153593963283294') 10153593963283294

parseInt('10153593963283295') 10153593963283296

parseInt('10153593963283296') 10153593963283296

parseInt('10153593963283297') 10153593963283296

parseInt('10153593963283298') 10153593963283298

Tested in browsers and node command line.

Thanks!

mardi 14 juin 2016

I'm trying to add the artist image at the background of an mp3 player in flash cs6, using actionscript3

Currently i am using this code. I am getting the image, but not in the background. Can someone please help me with this and also tell me how i can change the size of the image.

import flash.events.MouseEvent;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.media.SoundChannel;
import flash.media.SoundTransform; 

var binaryData:ByteArray;
var file:URLLoader = new URLLoader(new URLRequest("Stay With Me.mp3"));
var finalData:ByteArray = new ByteArray;
var byteCon:Loader = new Loader;
var offset:int; 
var rLength:int;
var found:Boolean = false;
var end:Boolean = false;
file.dataFormat = URLLoaderDataFormat.BINARY;
file.addEventListener(Event.COMPLETE, handleComplete);

function handleComplete(e:Event):void
{
    binaryData = file.data as ByteArray;
    binaryData.position = 0;

    while(!found){
        var pos:int = binaryData.readUnsignedInt();
        if(pos == 0x41504943){
            offset = binaryData.position + 20;
        }
        if(pos == 0){
            if (!found){
                rLength = binaryData.position - 1 - offset;
                if(rLength > 5000){
                    found = true;
                }
            }    
        }
        binaryData.position = binaryData.position - 3;
    }
    finalData.writeBytes(binaryData, offset, rLength);
    finalData.position = 0;
    byteCon.loadBytes(finalData);
    addChild(byteCon);

}

AS3 package issue

Really want to refactor and re-architect my project, it's become basically an 11k line monobloc that desperately needs to be split into multiple classes (and class files) inside a single package.

Yes I know I should have figured all this out when I started, but this is play not work and I was brand new to AS3 when I started. And I've kept building and building and it all works, it's just become very hard to manage.

My immediate goal is to define a package and then start breaking out function groups from the current main class into subclasses that extend the base. But I'm having a problem with the first step - defining the package.

I'm getting:

C:\Users\Vossie\Documents\Fex Line of Battle Project\trunk\line_of_battle\LOB_Core.as, Line 1, Column 1 5001: The name of package 'line_of_battle' does not reflect the location of this file. Please change the package definition's name inside this file, or move the file. C:\Users\Vossie\Documents\Fex Line of Battle Project\trunk\line_of_battle\LOB_Core.as

So I've checked:

package line_of_battle {
public class LOB_Core extends flash.display.MovieClip {

Filename is LOB_Core.as.

Path: Physical path on machine

I explicitly added it to the class search path:

Class path

So:

Name of package agrees with name of folder (I actually pasted it from folder to .as file)

Package file is within that folder.

Class search path includes that folder

Shouldn't matter for this but filename and public class name match

I've searched stack overflow and one similar case involved a text case mismatch that I don't see here. One other related question the guy's question turned into just how to make classes and name the files correctly.

According to the documentation I read, this should work fine. Can someone tell me what I am missing?

Embedding a large .flv into Adobe Flash results in noise-y results

I'm trying to import a rather large .flv into my otherwise empty Flash file in Adobe Animate CC.

The .flv in question enter image description here

Importing it (1) enter image description here

Importing it (2) enter image description here

After clicking Next and Finish, the video imports in about a second, very quickly for a huge video. The video appears on the stage much smaller than its actual size (160x120 pixels). The video itself looks nothing like what it's supposed to - in fact it looks like noise from a TV with bad reception.

My library window after importing enter image description here

AS3, clarification on the 'this' pointer

I am writing a program in flex, and I am having an issue with the this pointer.

I have a function call inside of a function and I am wondering which event my this pointer is passing.

private function funcA(someArgument)
{
    newDialog.show("Title", "Body", funcB, this) // the 'this' is the argument for funcB
}

private function funcB(CloseEvent:event)
{
   if(event == Event.CANCEL)
      doStuff;
   if(event == Event.COMPLETE)
      doOtherStuff;
}

To clarify, my question is, when I pass the this pointer into the function in the newDialog, am I passing my newly created Dialogue or am I passing in funcA. I'm thinking and hoping its the former.

I would just test this manually but the system is really large and currently tied in with other events so its difficult for me to just instantiate objects to test them.