mardi 31 mai 2016

Need to remove a child using hit test object function

i am trying to make a function where i drop some seeds into a bucket and the seeds are removed however the function will just be the seeds colliding with the bucket.

I have both of the objects as movieclips and have a basic hitTestObject conditional statement, i have no idea why the feed_mc wont be removed.

    if(bucket_mc.hitTestObject(feed_mc))
    {
    if(stage.contains(feed_mc))
    removeChild(feed_mc);
    }

thank you in advance

Flash + MDM Zinc - Build is Sluggish

We have a project created using Flash CS 5.5 with coding done in AS3. We use MDM Zinc for specific tasks like quitting the app, reading and writing data to DB, XML etc., and also to create the final exe file (Windows build).

Now, the problem is that when we run this exe, the app is sluggish. Particularly, it is sluggish only when the internet connection is ON. We ran a test by building with a barebones SWF. What this SWF does is, it will load three other SWFs when the corresponding button is pressed and in the background, a timeline animation is running.

The animation plays smooth as long as buttons to load external SWFs weren't clicked. As soon as a button is clicked, the animation freezes and the whole app slows down. PLUS this happens only when the network connection is turned on. If there's no network, the SWF loads normally and the animation is smooth.

We don't think this problem is related to the version of Windows OS (the slow-down occurs only in certain computers but with different versions of Windows OS in each). Could it be related to the graphics processing capability? The most obvious problem seems to be the network.

Any help would be greatly appreciated.

Thanks, Karthik.

AS3: Get class static variable from string

I'm trying to get a static variable of a class given an instance of the class. For example, the class name is MyClass and the static property I want to access is MyClass.myProperty, given an instance named myInstance. I use NameUtil.getUnqualifiedClassName(myInstance) to get the string "MyClass", but how do I get MyClass.myProperty from that string?

Fastest way to debug Adobe Air for Android with Native Extensions

I'm developing an Air for Android app that requires Native Extensions to perform tasks such as reading from the contacts and sending SMS messages.

Currently I am remotely debugging using Flash Professional and a physical Android Device over wifi.

The problem is that each time I debug the app it takes a while to transfer the app to the device over USB then connect to the debugger over a wifi connection from the device (about 2 minutes every time I need to debug). So in my case if I have to debug 30 times I've spent about an hour waiting to debug.

Is there a more streamline approach to speed this up? Maybe using an emulator or another solution?

Any help would be appreciated.

Way to handle colors visually/manually AND with code, in Flash/Animate?

I used to use a lot of Filters in Animate, and it was glorious because I could make a color filter by hand, see what it looks like, and then integrate code into that too, eg:

object.filters = e.currentTarget.filters;

But I'm trying to be good and stay away from filters to reduce processing power etc. Plus, filters don't take in hex codes. So I'm trying to use colorTransforms. But now things get really unwieldly because I figure out which colors I want, write down all the hex codes in Notepad, then write code to transform things to that color. And I still can't SEE the colours interacting until I publish the file. Isn't there SOME way to manually fiddle with colorTransforms? Maybe the Advanced section under Color Effect -> Style?

How I imagine this happening in my fantasy is: I have a few movieclips which interact to create a fabric swatch. I fiddle with the colorTransform or SOMEhow apply a hex code to them manually (not dynamically in code), and then I can use those swatches to dynamically color other things, something like:

newFabric.topPattern.colorTransform.color = fabricSwatch.topPattern.colorTransform.color;

I know I can do this if I added the colour using code first.. but is there any way to add the colour on the stage/visually/manually and then have the code roll it forward? I know I can draw a bitmap and sample a pixel's color, but the patterns all have very fine, different & complex shapes and transparencies so that won't work here :/

Socket communication between PHP server and ActionScript

I am studying about socket communication and succeeded to connect between PHP server and PHP client. Now I want to do same thing with PHP server and ActionScript client.

http://ift.tt/XpOOjr I read this and could communicate between server and client on 2 Windows command prompts both in PHP. So now I changed the client to ActionScript but it seems connecting to server but the string or number is not sent.

Does socket communication matter only address and port regardless of language? Or I cannot use two different languages to communicate?

For server, I used example 1 code in the URL above, changed address and port. AS client is here:

import flash.net.Socket;
import flash.events.*;

var s:Socket = new Socket;

function statusHandler(e:StatusEvent):void{
}

b.addEventListener(MouseEvent.CLICK, bsend);

s.addEventListener(StatusEvent.STATUS, statusHandler);
s.connect("localhost",10000);
s.addEventListener(ProgressEvent.SOCKET_DATA,sockread);

function bsend(e:MouseEvent):void{
    s.writeByte(Number(tin.text) );
    s.flush();
}

function sockread(e:ProgressEvent) : void{
    tout.text = String(s.readByte());
}

Actionscript 3.0 Write local XML

I am new to this website and also to AS3 programming.

Currently I am trying to write a local XML using Air. However everytime I press the button that generates the file, the .exe closes without saving the file.

The app instead works correctly when I test it in Animate (Ctrl+Enter) and the XML file is currently created and updated everytime.

Here's the code I am using:

import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.filesystem.File;
import flash.net.URLRequest;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
outButton.visible = false;
inButton.addEventListener(MouseEvent.CLICK, ingfx);

function ingfx(event: MouseEvent): void {
var prefsXML: XML = <gfx> 
<inout>1</inout>
<player>{selector_mc.selected_player}</player>
</gfx> ;
var file: File = File.documentsDirectory.resolvePath("c:\\test\\gfx.xml");
var fileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);

var outputString: String = '<?xml version="1.0" encoding="utf-8"?>\n';
outputString += prefsXML.toXMLString();

fileStream.writeUTFBytes(outputString);
fileStream.close();
inButton.visible = false;
outButton.visible = true;
}

Am I doing something wrong? I would like the app to stay open after the XML writing. Compiler shows no errors.

Thank you!

Actionscript 3.0 Eventhandler wrong timing

Currently I'm busy with Actionscript. I have a map with diverse worlds. If you click on an arrow icon you will scroll to the other world. The code is:

street.street_market.addEventListener(MouseEvent.CLICK, straat_actie2);

function straat_actie2(evt:MouseEvent) {

market.bringToFront();

MovieClip(root).worldmap.targetX = marktx;
MovieClip(root).worldmap.targetY = markty;

old = "street";
new = "market";
addEventListener(Event.ENTER_FRAME, fade);

}

The worlds are sliding to each other and the other one is fading out. It works like this:

addEventListener(Event.ENTER_FRAME, ballEnterFrame)
function ballEnterFrame (pEvent):void
{
var b = pEvent.currentTarget;
b.x += (b.targetX - b.x) / 16;
b.y += (b.targetY - b.y) / 16;
}

function fade(e:Event) 
{   
if(new != "")
{
    this[new].alpha+=0.03;
    if(this[old].alpha >= 0.2)
    {
        this[old].alpha-=0.05;
    }
}
}

It all works fine. Except one thing. The longer you stay on a world map the longer it will take to let the other world fade out. So if I stay on the street map for 10 secs and I scroll to the next one it takes around 10 seconds before the old map fades out.

Does someone know how I can solve this problem?

Thanks.

AS3 HTMLloader - How to work with sites?

I need to organize work in my AIR app with some sites (for example Facebook) by HTMLLoader and JS. Some things work quite well such window.document.getElementById or window.document.querySelectorAll, but does not work window.document.getElementsByAttribute for example.

I also need to get and set cookies, work via private proxy server, browser cache cleaning and search elements in the site DOM via Xpath.

Thanks for any advice.

How to add creation complete event after converting wav format to mp3 format using ffmpeg in Actionscript 3?

I am using the following codes to convert wav file format to mp3 file format using ffmpeg :

private var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
private var originalAudio:String = "C:\Users\User_Name\Desktop\test.wav";
info.executable = File.applicationDirectory.resolvePath("assets\\nativefiles\\ffmpeg.exe");
private var args: Vector.<String> = new Vector.<String>();
args.push("-i", originalAudio, "-vn", "-ar", "44100", "-ac", "2", "-ab", "192", "-acodec", "libmp3lame", "-f", "mp3", (tempDir.nativePath + '\\' + audioId + '.mp3'));
info.arguments = args;
private var nativeProcess:NativeProcess = new NativeProcess();
nativeProcess.start(info);
nativeProcess.addEventListener(Event.COMPLETE , onComplete);

protected function onComplete(event:Event):void
{
    trace("Conversion Completed");
}

But problem is that I am unable to trace the complete event control after file conversion. I have already added a complete event on nativeprocess (i.e nativeProcess.addEventListener(Event.COMPLETE , onComplete); but the control not coming in to the function onComplete after conversion.

So any body have an idea why the control not coming into the function or how to add event listener to trace complete event function.

lundi 30 mai 2016

Can I colorTransform a MovieClip but exclude specific sub-components?

Scenario:

I have floating islands that move around in odd paths. There are torches (nested movieClips) mounted on some of the islands. Sometimes a weather effect will change the color and brightness of the islands. Is there a way to change the brightness of the islands (parent movieClips) without also changing the brightness of the torches (child movieClips)?

===================================================

One solution that I can conceive is independently color adjusting all the child objects of each movieClip, instead of adjusting the parent object. This seems highly inconvenient and unnecessary though, so any thoughts would be appreciated.

Adobe AIR iOS Compiling with ANEs

I'm impliment the Game Center ANE provided by Adobe to my AIR game for iOS developed in Adobe Flash CC 2015. I downloaded the latest ANE, which should be 64bit, but when I try to compile the file, or even export movie (Ctrl + Enter), I get this error:

Test Movie terminated.
The content cannot be loaded because there was a problem loading an extension: Error: Requested extension com.adobe.ane.gameCenter is not supported for Windows-x86.

When I tried using the "gameCenter.ane"-file included in the Gaming SDK by Adobe, I got an error saying:

META-INF/ANE/iPhone-ARM/libgameCenter.aare required to have universal iOS libraries. Please contact the ANE developer(s) to get the same.

I was able to export movie (Ctrl + Enter) with the original included gameCenter.ane file (from Gaming SDK), but not while using the 64bit.

Any ideas?

Thanks!

When i want to move my player with the keyboard, once i let go of the arrow keys the player keeps moving. (AS3)

public function keyD(p:KeyboardEvent):void { trace(p.keyCode); //a=65 d=68 w=87 s=83 //to program the 4 arrow keys if (p.keyCode==Keyboard.LEFT) { vx=-5; } else if (p.keyCode==Keyboard.RIGHT) { vx=5; } else if (p.keyCode==Keyboard.UP) { vy=-5; } else if (p.keyCode==Keyboard.DOWN) { vy=5; } } public function keyU(e:KeyboardEvent):void { //we want to program the 4 arrow keys if (p.keyCode==Keyboard.LEFT) //Make player move left { vx=0; } else if (p.keyCode==Keyboard.RIGHT) //Make player move right { vx=0; } else if (p.keyCode==Keyboard.UP) //Make player move up { vy=0; } else if (p.keyCode==Keyboard.DOWN) //Make player move down { vy=0; } }

public function gameLoop(e:Event):void { //this function is called 24 times each second

    p.x+=vx;//move the player horizontally
    p.y+=vy;//move the player vertically

How to open a mp4 local file using default application - AIR?

I've been trying to open a local video (mp4) as an AIR application using an android tablet, no success.

I've tryed to use URL adress but did not work as well.

I want to create a button that when pressed will open a internal .mp4 video using default android application to run this video. LIke opening a external webpage, but with video.

the video is located: /storage/extSdCard/Dealer Manager/10_VIDEOS/01_VIDEOS_COLHEDORA/Demonstração Grupo Biosev/video02.mp4

If someone could help me with that I would be very grateful.

Regards,

How to find total frame and current frame of a swf when playing in wpf web browser?

Here I have played swf in wpf web browser control. I just want to know how to get total frame and current frame of a swf when playing in web browser.The following code is used to find these counts when using shockwaveflash object.Instead of these code what we have in web browser and c#.

int fn = axShockwaveFlash1.TotalFrames;
int cf = axShockwaveFlash1.CurrentFrame();

Adobe Flash: How to join several separate .swf files into one .exe file?

Noob ask: I have many separate .swf files, they are like stairs.. for example:

menu.swf load scene1.swf

scene1.swf load scene2.swf and so on...

There is a button in menu.swf to load scene1.swf and there is a button in scene1.swf to load scene2.swf and so on...

*every .swf file has it own code, I use Adobe Flash CS6 and Actionscript 3.0 I use loader to load those .swf file

var myLoader:Loader = new Loader();                     
var intro:URLRequest = new URLRequest("Intro.swf");     
myLoader.load(intro);                                   
addChild(myLoader); 

My problem: When I create project on menu.swf to menu.exe... press the button... it can't load any .swf file.. T-T"

so.. what should I do..?

here is sample of my project: http://ift.tt/1OXbmw4

*based on my project Little Red Riding Hood.swf is the main menu. It works fine when I run it with .swf

send json data to array(movieclip) as3.0

I am building an air app in flash cs6 using as3. I need to send a json to movieclip. I wanted to create a "timeline" on my application. This is the code I use.

function onCompleteLoadTimeline(event:Event){
    var result:Object = JSON.parse(event.target.data);
    var yPos = 0;
    for (var h:int=0; h<=1; h++){
        tpost = new t_post();
        tpost.x = 0;
        tpost.y = 0;
        timeline_mc.addChild(tpost);
        timeline_container.push(tpost);
        timeline_container[h].y = yPos;
        yPos += timeline_container[h].batas.y;

    }
    for (var i:Object in result){
        for (var j:int=0; j<=1; j++){
            timeline_container[j].nama.text = result[i].timeline_name;
            timeline_container[j].postingan.text = result[i].timeline_post;
        }
        trace ("nama : "+result[i].timeline_name);
        trace ("status : "+result[i].timeline_post);
        trace ("waktu : "+result[i].date);
        trace ("suka : "+result[i].likers);
    }
}

for the code only the latest data appear in the movie clip. please help me.

dimanche 29 mai 2016

Which one should I choose?? Adobe Animate CC (AS3) or Unity (C#)?

This is something Im wondering about in terms of 2d game development because Im a freshman and I want to focus on game development as a career. I was wondering which software I should use over the course of high school so I can harness my schools before I enter the industry.

i wan to create search feature in as3

i wrote this code to my search feature in as3 but it is not good work! because when i click on my button module search doing wrong!!! please help me!!!!please look at my cod when i write (123456789123).my module trace correct and when write (1234567899) my module trace correct again????!!!! how can i correct this problem; this link is my sample: http://ift.tt/1TQFwq8 or Click here

How do i detect collision and stack falling objects in as3 flash?

I have a little problem when I'm trying to get the sqares to stack, almost like in tetris. I don't know how I can controll the different squares so i can check for collision. I have made one square with as3 linkage name Square.

    var timer:Timer = new Timer(12);

    timer.addEventListener(TimerEvent.TIMER, doStuff);

    timer.start();

    var newSquare= new Square();
    nyFirkant.y = 0;
    nyFirkant.x = Math.floor( Math.random() * 4) * 100;
    addChild(newSquare);

    stage.addEventListener(KeyboardEvent.KEY_DOWN, tastLytter);

    function keyListener(evt:KeyboardEvent)
    {
    var key:int = evt.keyCode;

    if (key== Keyboard.RIGHT && newSquare.x < 400)
      {
        newSquare.x +=  100;
    }
   if (key== Keyboard.LEFT && newSquare.x > 0)
    {
        newSquare.x -=  100;
    }

    }


    function doStuff(evt:TimerEvent)
    {
    if (newSquare.y <= 400 - newSquare.height)
    {
        newSquare.y = newSquare.y + 2;
    }
    if (newSquare.y == 350)
    {
        newSquare= new Square();
        newSquare.y = 0;
        newSquare.x = Math.floor( Math.random() * 4) * 100;;

        addChild(newSquare);

    }



    }

samedi 28 mai 2016

How can i remove extra black space in a movie clip in flash

In flash Cs6 or CC when i convert a image into movie clip no matter what kind of image is that it will take e square shape with extra space.

lets say a pyramid shape image which has two side, narrow side and wide side if i convert it into a movie clip its always taking a square shape with extra space in both side. (Narrow side)

its creating a big problem in my game where i use (hitTestObject). Is there any way to solve it.

Is it possible to run multiple Air clients in the same project (Intellij IDEA)

Basically, I need to test some multiplayer functionality, and it would be more than useful to have two Air instances running at the same time.

The only way I could achieve this was creating two different projects, however it's quite cumbersome.

Is there any way to do it inside the same project?.

It is possible to do it if you use the Flash player instead though.

vendredi 27 mai 2016

Update text field into movieclip from main timeline code

im working in a proyect for basketball, i have an issue, all my code works great if all my components are in the main timeline.

But as soon as i convert the textfields into a movieclip so i can animate and apply alfa value, all stops working.

what im i doing wrong?? the only solution that i think of was, writing the result of my countdown into the text field in the movieclip but i didnt worked it out.

this is my code.

function onTimer ( ev:TimerEvent ) : void {
timeRemaining--;
if (timeRemaining < 0) {
    timeRemaining = 0;
    loseGame();
}
else 
    showTime.text = formatTimeRemaining ();
    var miReloj:MovieClip;
    var titulo_txt:TextField = new TextField();
    titulo_txt.text = formatTimeRemaining ();
    addChild(miReloj);
    miReloj.addChild(titulo_txt);
    // miReloj.addChild(showTime1.text);
     //miReloj.showTime1.text = formatTimeRemaining ();

}

send an array from php to as3.0

I am building an air app in flash cs6 using as3. I need to send an array from php to flash as3.0 I wanted to create a "timeline" on my application. I have a lot of reading various references, but not much help. This is the code I use. timeline.php file

require_once "connect.php";
$action = isset($_GET['action'])?$_GET['action']:'';
$body_nama = array();
$body_postingan = array();
$total_likers = array();
$id = array();
switch($action){
    case 'posting':
    posting();
    break;
    case 'like':
    like();
    break;
    case 'delet_ini':
    deletIni();
    break;
    case 'load_timeline':
    loadTimeline();
    break;
    case 'load_timeline_lama':
    loadTimelineLama();
    break;
}
function loadTimeline(){
    global $body_nama;
    global $body_postingan;
    global $total_likers;
    global $id;

    $query_total = "SELECT COUNT(*) FROM timeline_posts";
    $result_total = mysql_query($query_total);
    $total = mysql_result($result_total,0);

    for ($i =0; $i<=9; $i++){
        $query_timline = "SELECT * FROM timeline_posts WHERE id = ('$total'-'$i')";
        $result = mysql_query($query_timline);
        while ($data = mysql_fetch_array($result)){
            $body_nama[$i] = htmlentities($data['timeline_name']);
            $body_postingan[$i] = htmlentities($data['timeline_post']);
            $id[$i] = htmlentities($data['id']);
            print "nama[$i]=$body_nama[$i]";
            print "postingan[$i]=$body_postingan[$i]";
            print "id[$i]=$id[$i]";
        }
    }
}

and here is as3.0 code

function loadTimeline(){
    var phpFileRequest:URLRequest = new URLRequest("http://localhost/social_media_1/timeline.php?action=load_timeline");
    var phpLoader:URLLoader = new URLLoader();
    phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
    phpLoader.addEventListener(Event.COMPLETE, onCompleteLoadTimeline);
    phpLoader.load(phpFileRequest);

    function onCompleteLoadTimeline(event:Event){

        trace (event.target.data.nama[0]);
        trace (event.target.data.postingan[0]);
        trace (event.target.data.id[0]);

    }
}

but I have error. TypeError: Error #1010: A term is undefined and has no properties. at Function/MasagiApp_fla:MainTimeline/loadTimeline/MasagiApp_fla:onCompleteLoadTimeline()[MasagiApp_fla.MainTimeline::frame6:52] at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at flash.net::URLLoader/onComplete()

please help me

Dynamic Text Fields on Top

In my Adobe Flash game, I have two dynamic text fields placed on stage. The graphics for the game are made using Actionscript 3. No matter what, the blocks generated by the code always cover up the text. Can anyone help?

AS3 for Air events issues

I'm having a bit of a problem understanding why some events don't fire when calling a function from within another function.

Here's what happens and I can't figure out why:
when there is no test.xml file in the app storage directory writecamfile() executes, but then it seems the oncomplete() function never fires. the preloader remains visible and the trace does not work.
if the file exists, readcamfile() fires just fine, oncomplete hides the preloader and returns the trace.

My question is why doesn't oncomplete() fire when there is no test.xml file? My logic was to check for the file if it does not exist, create it and then read it.

Any pointers are greatly appreciated. Thank you in advance and have a great day!

Tony

    package util
    {
    import flash.filesystem.*;
    import flash.display.Sprite;
    import flash.display.MovieClip;
    import flash.events.*;
    import flash.display.*;
    import flash.events.Event;
    import flash.events.MediaEvent;
    import flash.events.MouseEvent;
    import flash.media.CameraUI;    
    import flash.media.MediaPromise;
    import flash.media.MediaType;
    import fl.containers.*;
    import fl.controls.*;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.net.URLVariables;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequestMethod;

    dynamic public class cam5 extends MovieClip
    {
    public var preloader:MovieClip;
    public function cam5()
    {
        var tmp_file:File = File.applicationStorageDirectory.resolvePath('test.xml');
        if (tmp_file.exists)
        {// File exists
            preloader.visible = true;
            readcamfile(null); // check settings from the camera file

        } else
        {// File doesn't exist
            writecamfile();
            preloader.visible = true;
        }
        function readcamfile(event:Event):void
        {
            var loader:URLLoader = new URLLoader(new URLRequest(File.applicationStorageDirectory.resolvePath('test.xml').url));
            loader.addEventListener(Event.COMPLETE, oncomplete);
        }

        function writecamfile():void
        {
            var xmlstr:XML = <images></images>;
            var file:File = File.applicationStorageDirectory.resolvePath("test.xml");
            var fileStream:FileStream = new FileStream();
            fileStream.open(file, FileMode.WRITE);
            var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';
            outputString += xmlstr.toXMLString();
            fileStream.writeUTFBytes(outputString);
            fileStream.addEventListener(Event.COMPLETE, readcamfile);
            fileStream.close();         
        }

        function oncomplete(event:Event):void
        {
            var xml:XML = new XML(event.currentTarget.data);

            var chkcount : Boolean = (xml.children().length() > 0);

            if(chkcount)
            {
                var xmlcount:int = xml.children().length(); //test children count
                var camXMLList:XMLList = xml.img;
                var count:int = camXMLList.length(); //test list count

                for(var i:int=0; i<xmlcount; i++)
                {
                    var _row = xml.children()[i];
                }
                preloader.visible = false;
                trace(_row.text()+'\n'+xmlcount+'\n'+count);
            }else
            {
                preloader.visible = false;
                trace("no images");
            }

        }           
    }
    }
    }

jeudi 26 mai 2016

Group / split string into 2's set

This i probably a dumb question but it beats me.

The same thing in Python works perfectly, tho in AS3 doesn't.

var s:String = "123456";
trace(s.split(/../gm));

Expecting this as array: ['12','34','56'] but instead i get: [,,]

I have experimented various regexr patterns but none splitted into 2-char batches.

Any ideas / solutions ?

Actionscript 3; how to make a toggle button?

Currently making a button that will toggle the visibility of a movie clip on and off. Here is my code;

infoButton.addEventListener(MouseEvent.CLICK, howToPlay);


var boxUp:Boolean = false;

function howToPlay(event:MouseEvent):void 
{
    if(boxUp == false)
    {
        infoBox.visible = true;
        boxUp = true;
    }
    if(boxUp == true){
        infoBox.visible = false;
        boxUp = false;
    }


}

However when clicking the button nothing happens. I'm assuming this is because it's a self contradicting function, however I don't know any other way to store if the movie clip is visible or not.

Can anyone help?

Implicit coercion of a value of type Number to an unrelated type flash.display:MovieClip

When I try to pass a MovieClip through a function I get the error:

"Implicit coercion of a value of type Number to an unrelated type flash.display:MovieClip"

public var generatedRoom:Array;

public function enemyPack():void
    {
        //trace(generatedRoom[createdRooms]);
        var random:int = Main.getRandom(0,5);

        switch(random)
        {
            case 0:
                Main.spawnEnemy(roomX+Main.getRandom(50, room.width-50),generatedRoom[createdRooms],roomY+Main.getRandom(50, room.height-50));
                break;
        }
    }

and when I trace the variable it returns [object MC_"myMovieClip"]

AS3; can't detect collision with child?

I'm currently trying to detect a collision with a spawned movie clip, shown below;

    function fruitCollide(e:Event):void
    {
        if(player_mc.hitTestObject(myApple))
           {
               trace("Hit!")
                player_mc.removeEventListener(Event.ENTER_FRAME, moveThePlayer);
                currentWordSpawn = "apple";
                spawnText();
           }
}

The things the player is colliding with are defined earlier in the program;

//Movie Clip Spawns
var myApple = new apple();
var myPear = new pear();
var myTomato = new tomato();
var myWatermelon = new watermelon();

The above spawns fine on the screen, however when the player walks over them, nothing happens. The player actually goes behind the spawned fruit, and there is no collision detected.

What have I done wrong? How do I detect a collision with a movie clip spawned via code?

Thanks for any help.

mercredi 25 mai 2016

Making "rooms" connected and detecting where the player is

new to SO and pretty new to AS3.

I've been programming a random "room" generator where each room is connected to each other, problem is I don't know how to detect which room is the player on so I can make collisions on that specific area.

This is part of the room generation code

public function RoomGen()
    {
        upDoorArray = new Array();
        downDoorArray = new Array();
        leftDoorArray = new Array();
        rightDoorArray = new Array();
        generatedRoomX = new Array();
        generatedRoomY = new Array();

        rootRoom = new MC_Fondo();
        if(generate == true)
        {
            for(var i:int = 0; i<=maxRooms; i++)
            {
                room = new MC_Fondo();

                upDoor = new MC_Door();
                downDoor = new MC_Door();
                leftDoor = new MC_Door();
                rightDoor = new MC_Door();

                rand = Math.random()*4;
                //rand = 0;
                randType = Math.random()*3;
                //randType = 1;


                if(rand == 0 && up == false)
                {
                    up = false;
                    down = true;
                    left = false;
                    right = false;

                    upDoor.x = roomX + (room.width/2);
                    upDoor.y =  roomY - upDoor.height/2 +15;
                    //room.addChild(upDoor);
                    Main.render.addChild(upDoor);
                    upDoorArray.push(upDoor);
                    if(i>0)
                    {
                        roomY -= room.height;
                    }
                    else
                    {
                        rootRoom = room;
                    }

                    room.x = roomX;
                    room.y = roomY;
                    Main.render.addChild(room);
                    generatedRoomY.push(room);
                    if(randType == 0)
                    {

                    }
                    else if(randType == 1)
                    {
                        enemyPack();
                        roomEnemiesArray.push(roomEnemies);
                    }
                    else if(randType == 2)
                    {

                    }
                    downDoor.x = roomX + (room.width/2);
                    downDoor.y = roomY + room.height;
                    downDoor.scaleY = -1.0;
                    Main.render.addChild(downDoor);
                    downDoorArray.push(downDoor);
                }

                if(rand == 1 && down == false)
                {
                    up = true;
                    down = false;
                    left = false;
                    right = false;

                    downDoor.x = roomX + (room.width/2);
                    downDoor.y = roomY + room.height;
                    downDoor.scaleY = -1.0;
                    Main.render.addChild(downDoor);
                    downDoorArray.push(downDoor);

                    if(i>0)
                    {
                        roomY += room.height;
                    }
                    else
                    {
                        rootRoom = room;
                    }

                    room.x = roomX;
                    room.y = roomY;
                    Main.render.addChild(room);
                    generatedRoomY.push(room);

                    if(randType == 0)
                    {

                    }
                    else if(randType == 1)
                    {
                        enemyPack();
                        roomEnemiesArray.push(roomEnemies);
                    }
                    else if(randType == 2)
                    {

                    }

                    upDoor.x = roomX + (room.width/2);
                    upDoor.y = roomY - upDoor.height/2 +15;
                    Main.render.addChild(upDoor);
                    upDoorArray.push(upDoor);
                }

                if(rand == 2 && right == false)
                {
                    up = false;
                    down = false;
                    left = true;
                    right = false;

                    rightDoor.x = roomX + room.width;
                    rightDoor.y = roomY + (room.height/2) - rightDoor.width/2;
                    rightDoor.rotation = 90;
                    Main.render.addChild(rightDoor);
                    rightDoorArray.push(rightDoor);


                    if(i>0)
                    {
                        roomX += room.width;
                    }
                    else
                    {
                        rootRoom = room;
                    }

                    room.x = roomX;
                    room.y = roomY;
                    Main.render.addChild(room);
                    generatedRoomX.push(room);

                    if(randType == 0)
                    {

                    }
                    else if(randType == 1)
                    {
                        enemyPack();
                        roomEnemiesArray.push(roomEnemies);
                    }
                    else if(randType == 2)
                    {

                    }

                    leftDoor.x = roomX;
                    leftDoor.y = roomY + (room.height/2) + leftDoor.width/2;
                    leftDoor.rotation = -90;
                    Main.render.addChild(leftDoor);
                    leftDoorArray.push(leftDoor);
                }

                if(rand == 3 && left == false)
                {
                    up = false;
                    down = false;
                    left = false;
                    right = true;

                    leftDoor.x = roomX;
                    leftDoor.y = roomY + (room.height/2) + leftDoor.width/2;
                    leftDoor.rotation = -90;
                    Main.render.addChild(leftDoor);
                    leftDoorArray.push(leftDoor);
                    if(i>0)
                    {
                        roomX -= room.width;
                    }
                    else
                    {
                        rootRoom = room;
                    }
                    room.x = roomX;
                    room.y = roomY;
                    Main.render.addChild(room);
                    generatedRoomX.push(room);

                    if(randType == 0)
                    {

                    }
                    else if(randType == 1)
                    {
                        enemyPack();
                        roomEnemiesArray.push(roomEnemies);
                    }
                    else if(randType == 2)
                    {

                    }

                    rightDoor.x = roomX + room.width;
                    rightDoor.y = roomY + (room.height/2)- rightDoor.width/2;
                    rightDoor.rotation = 90;
                    Main.render.addChild(rightDoor);
                    rightDoorArray.push(rightDoor);
                }
                createdRooms++;
            }
        }
        Main.mainStage.addEventListener(Event.ENTER_FRAME, roomCollision);
    }

which results in something like this:

result

as you can see mobs spawn on specific rooms and so is the player(which spawns on the first room generated), so how could I detect which room the player is on right now and add collisions to that specific room.

Issue with Flash AS3 Player movieclip and creating an instance

So heres my issue, I created a movieclip class within Adobe Animate (Warmage.as) and I added it to my stage (addChild(char)). I tried to access the properties says undefined property of char. But I created a class for Warmage and created an instance of it (char).

package  
{

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Timer;

public class Main_class extends MovieClip
{
    //player stats
    var hsp:Number = 0;
    var vsp:Number = 0;
    var floor:Number = 1318;
    var attackCounter = 5;
    var doubleJumpCount = 0;

    //Player states
    var rightSide:Boolean = false;       
    var rDown:Boolean = false;
    var lDown:Boolean = false;
    var jumped:Boolean = false;
    var onGround:Boolean = false;
    var crouchMode:Boolean = false;
    var attackMode:Boolean = false;
    var canDoubleJump = false;

    public function Main_class()
    {
         var char:Warmage = new Warmage();//Adds player to the level
         char.x = 500;
         char.y = 300;
         addChild(char);

         stage.addEventListener(Event.ENTER_FRAME, gameLoop);//Stage listens no matter what
         stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
         stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
    }
    function gameLoop(e:Event):void
    {
        if(rDown)
          {
             char.x += 10;
          }
        if(lDown)
          {
             char.x -= 10; 
          }
    }
    function keyPressed(e:KeyboardEvent):void
    {
        if(e.keyCode == Keyboard.RIGHT)
          {
             rDown = true;  
          }
        if(e.keyCode == Keyboard.LEFT)
          {
             lDown = true;
          }
        if(e.keyCode == Keyboard.UP && onGround)
          {
             jumped = true;
             //doubleJumpCount += 1;
          }
        if(e.keyCode == Keyboard.DOWN && onGround)
          {
             crouchMode = true; 
          }
        if(e.keyCode == Keyboard.SPACE && onGround)
          {
              attackMode = false;
          }
    }
    function keyReleased(e:KeyboardEvent):void
    {
        if(e.keyCode == Keyboard.RIGHT)
          {
             rDown = false; 
          }
        if(e.keyCode == Keyboard.LEFT)
          {
             lDown = false;  
          }
        if(e.keyCode == Keyboard.UP)
          {
             jumped = true;  
          }
        if(e.keyCode == Keyboard.DOWN)
          {
             crouchMode = false; 
          }
        if(e.keyCode == Keyboard.SPACE)
          {
             attackMode = true;
          }
    }

}
}

As3 + PHP error

Im gettin this error using as3 votingpoll. I dont understand what is wrong, since i only know basic coding. I really would need to get this working for a school project.

Hope any one can help me out ! Thanks alot

at flash.text::TextField/set text()
at Onlinepoll_fla::WholePoll_1/completeHandler()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()

AS3 code request:

stop(); // Stop the timeline since it does not need to travel for this to run

// Assign a variable name for our URLVariables object
var variables1: URLVariables = new URLVariables();

//  Build the varSend variable
var varSend1: URLRequest = new URLRequest("parse_my_poll.php");
varSend1.method = URLRequestMethod.POST;
varSend1.data = variables1;

// Build the varLoader variable
var varLoader1: URLLoader = new URLLoader;
varLoader1.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader1.addEventListener(Event.COMPLETE, completeHandler1);

// Set variable to send to PHP here for the varloader below
variables1.myRequest = "load_numbers";


// Send data to php file now, and wait for response using the COMPLETE event
varLoader1.load(varSend1);

function completeHandler1(event: Event): void {
    count1_txt.text = "" + event.target.data.choice1Count;
    count2_txt.text = "" + event.target.data.choice2Count;
    count3_txt.text = "" + event.target.data.choice3Count;
}

**as3 Send code**
// hide the little processing movieclip
processing_mc.visible = false;

// Initialize the choiceNum variable that we will use below
var choiceNum:Number = 0;

// Set text formatting colors for errors and success messages
var errorsFormat:TextFormat = new TextFormat();
errorsFormat.color = 0xFF0000; // bright red

var successFormat:TextFormat = new TextFormat();
successFormat.color = 0x00FF00; // bright green

/////////////////////////////////////////////////////////////
// Button Click Functions
function btn1Click(event:MouseEvent):void{
    choiceNum = 1;
    choice_txt.text = choice1_txt.text;
}
function btn2Click(event:MouseEvent):void{
    choiceNum = 2;
    choice_txt.text = choice2_txt.text;
}
function btn3Click(event:MouseEvent):void{
    choiceNum = 3;
    choice_txt.text = choice3_txt.text;
}
// Button Click Listeners
btn1.addEventListener(MouseEvent.CLICK, btn1Click);
btn2.addEventListener(MouseEvent.CLICK, btn2Click);
btn3.addEventListener(MouseEvent.CLICK, btn3Click);

//////////////////////////////////////////////////////////////
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();

//  Build the varSend variable
var varSend:URLRequest = new URLRequest("parse_my_poll.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;

// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);

// Handler for PHP script completion and return
function completeHandler(event:Event):void{
    // remove processing movieclip
    processing_mc.visible = false;
    // Clear the form fields
    choice_txt.text = choice1_txt.text;
    choiceNum = 0;
    // Load the response from the PHP file
    status_txt.text = event.target.data.return_msg;
    status_txt.setTextFormat(errorsFormat);
    if (event.target.data.return_msg == "Thanks for voting!") {
        // Reload new values into the count texts only if we get a proper response and new values
        status_txt.setTextFormat(successFormat);
        count1_txt.text = "" + event.target.data.choice1Count;
        count2_txt.text = "" + event.target.data.choice2Count;
        count3_txt.text = "" + event.target.data.choice3Count;
    }  
}

// Add an event listener for the submit button and what function to run
vote_btn.addEventListener(MouseEvent.CLICK, ValidateAndSend);

// Validate form fields and send the variables when submit button is clicked
function ValidateAndSend(event:MouseEvent):void {
    //validate form fields
    if(!choice_txt.length) {  
        // if they forgot to choose before pressing the vote button
        status_txt.text = "Please choose before you press vote.";  
        status_txt.setTextFormat(errorsFormat);

    } else {
        status_txt.text = "Sending...";
        processing_mc.visible = true;
        // Ready the variables for sending
        variables.userChoice = choiceNum;
        variables.myRequest = "store_choice";  
        // Send the data to the php file
        varLoader.load(varSend);
    } // close else after form validation

} // Close ValidateAndSend function ////////////////////////

PHP code:

<?php
/* 
::::::::::Script Written By: Adam Khoury @ www.developphp.com:::::::::::::
:::::::::If you find www.developphp.com tutorials helpful or handy:::::::::::::
:::::::::::please link to it wherever possible to help others find it::::::::::::::::
*/
// ---------------------------------------- Section 1 -----------------------------------------------
//  IMPORTANT!!!! Connect to MySQL database here(put your connection data here)
mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("data") or die (mysql_error());

// When Flash requests the totals initially we run this code
if ($_POST['myRequest'] == "load_numbers") {

    // Query the totals from the database
    $sql1 = mysql_query("SELECT id FROM votingPoll WHERE choice='1'"); 
    $choice1Count = mysql_num_rows($sql1); 
    $sql2 = mysql_query("SELECT id FROM votingPoll WHERE choice='2'"); 
    $choice2Count = mysql_num_rows($sql2); 
    $sql3 = mysql_query("SELECT id FROM votingPoll WHERE choice='3'"); 
    $choice3Count = mysql_num_rows($sql3); 

    echo "choice1Count=$choice1Count";
    echo "&choice2Count=$choice2Count";
    echo "&choice3Count=$choice3Count";

}

// ---------------------------------------- Section 2 -----------------------------------------------
// IF POSTING A USER'S CHOICE
if ($_POST['myRequest'] == "store_choice") {

    //Obtain user IP address 
    $ip = $_SERVER['REMOTE_ADDR'];
    // Create local variable from the Flash ActionScript posted variable
    $userChoice   = $_POST['userChoice'];
    $sql = mysql_query("SELECT id FROM votingPoll WHERE ipaddress='$ip'");
    $rowCount = mysql_num_rows($sql);
    if ($rowCount == 1) {

        $my_msg = "You have already voted in this poll.";
        print "return_msg=$my_msg";

    } else {

        $sql_insert = mysql_query("INSERT INTO votingPoll (choice, ipaddress) VALUES('$userChoice','$ip')")  or die (mysql_error());
        $sql1 = mysql_query("SELECT * FROM votingPoll WHERE choice='1'");
        $choice1Count = mysql_num_rows($sql1);
        $sql2 = mysql_query("SELECT * FROM votingPoll WHERE choice='2'");
        $choice2Count = mysql_num_rows($sql2);
        $sql3 = mysql_query("SELECT * FROM votingPoll WHERE choice='3'");
        $choice3Count = mysql_num_rows($sql3);
        $my_msg = "Thanks for voting!";
        echo "return_msg=$my_msg";
        echo "&choice1Count=$choice1Count";
        echo "&choice2Count=$choice2Count";
        echo "&choice3Count=$choice3Count";
    }
}
?>

Can someone help me flip this Actionscript 3 graphic?

newPlacement = new Block();
        newPlacement.graphics.beginFill(0xFFFFFF);
        newPlacement.graphics.drawRoundRect(0, 0, 25, 25, 9);
        newPlacement.graphics.endFill();
        newPlacement.graphics.beginFill(0xFFFFFF);
        newPlacement.graphics.drawRect(0,0,10,25);
        newPlacement.graphics.endFill();
        blockHolder.addChild(newPlacement);

Here is code I am using in Flash to draw a square object on the stage that is jagged on the left and rounded on the right. Can anyone help me figure out how to code the flipped image of this (a square object that is rounded on the left and jagged on the right). Thanks!

prevent swf from caching an external image

I have a swf which loads external image and texts.code used in action script is

loadMovie("pics/pic002.png", _root.pic2.empty);

Now if I replace pic002.png with some image ,In firefox the swf does not load new image instead it displayed the cached image.But it work fine with chrome. In order to avoid caching i used the below code

loadMovie("pics/pic002.png?rand="+new Date().getTime(), _root.pic2.empty);

But it throws error as
Error opening URL 'http://file/C|/xmpp/xampplite/htdocs/surewaves%5Ffire/new%5Fdynamic%5Fcontent/pics/pic002.png?rand=1464190037815

I have also used meta tags to avoid caching in browser like

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

how to prevent it

How to access the swf file when playing in wpf web browser?

Hi here I am using wpf web browser to play swf file and I just want to know how to find the current frame and total frame of a swf file.Then how to access the swf file like play/pause.

this.MainBrowser.Navigate(@"C:\Users\Admin\Desktop\array-file-final020.swf");

this is the code I have used to play swf also I just want to know is it possible to communicate swf file with wpf web browser.

(ActionScript 3.0) My function is not updating the global variable via Button Event

I am trying to figure out how to update my global variable. At the moment I am just shoving all my code at ActionScript 3 frame, instead of using external ActionScript file.

Nevertheless here is my code:

import flash.ui.Keyboard;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;

var SPEED:int = 10;
var speed_multiplier:int = 1;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
multiplier_two.addEventListener(KeyboardEvent.CLICK, twoButton);

function keyDown(e:KeyboardEvent):void {
   switch(e.keyCode) {
      case(Keyboard.LEFT):
         character.x -= SPEED*speed_multiplier;
         collisionDetection(3);
         break;

      case(Keyboard.RIGHT):
         character.x += SPEED*speed_multiplier;
         collisionDetection(4);
         break;

      case(Keyboard.UP):
         character.y -= SPEED*speed_multiplier;
         collisionDetection(1);
         break;

      case(Keyboard.DOWN):
         character.y += SPEED*speed_multiplier;
         collisionDetection(2);
         break;
   }
}

function twoButton(e:MouseEvent):void {
    speed_multiplier = 2;
}

I already did a trace, to make sure is working properly. The click event for the button is working fine. However my gloval variable for speed_multiplier is not being updated when I click on the button.

mardi 24 mai 2016

How to configure Flex Unit 4.2 in without Flash Builder

I'm working on a project that uses the Flash IDE as the compiler and asset manager. This means I'm using as3, with Flash Develop.

All Apache documentation I have found is either MXML specific, or relies on the wizard in Flash Builder. Are there better resources that exist describing how the Flex Unit classes should be used in a non Flash Builder context?

How do you handle mouseover events with overlapping TextFields?

I have a horizontal stack of buttons that represent tabs, and each button has a TextField inside of it that is larger than the dimensions of the button so that they overlap. Like this (the dotted line is a TextField and the red box is the area where mousing over does not work due to the overlap):

enter image description here

Each of these buttons is an instance of a TabButton, which has a class definition like this:

package src
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.text.TextField;

    public class TabButton extends MovieClip
    {
        // Stage Instances
        public var mcHitZone:MovieClip;
        public var mcText:TextField;

        public function TabButton()
        {
            super();

            addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
        }

        private function onAddedToStage(e:Event):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);

            // Disable mouse input on everything except for the hit zone since that's where mouse handling should be done.
            mcText.mouseEnabled = false;

            mcHitZone.addEventListener(MouseEvent.ROLL_OVER, onMouse, false, 0, true);
        }

        private function onMouse(e:MouseEvent):void
        {
            trace("Mouse event: " + name + " " + e.type);
        }
    }
}

Each TabButton has a mcHitZone that I'm attaching the mouse handler to, which is the black area on the above image. Since the TextField is much larger than the button itself, it needs to be completely ignored for mouse input handling so I'm turning it off with mcText.mouseEnabled = false;, which seems to work when mousing within a single button, but when mousing over the overlap area (the red box) the TextField will block mouse input from the other button.

Is there any way to make this work so that the TextField does not block mouse input on anything that it overlaps with?

I've uploaded the FLA and AS that I've been testing this with here. If you run it, it will trace when you roll over a particular button. If you try to mouse over the red area of the leftmost button then it won't work.

AS3 Display random word from array onto stage

I have an array of words in my code. What I'm hoping to do is display, at random, one word from the array onto the stage. How is this achievable?

ActionScript 3.0; looping audiofiles

Currently trying to loop a sound clip (imported mp3 to library) endlessly in my Actionscript 3 project. This is my current set up:

var sound:Sound = new bgm();
function playSound():void
{
    var channel:SoundChannel = sound.play(80);
    channel.addEventListener(Event.SOUND_COMPLETE, onComplete);
}

function onComplete(event:Event):void
{
    SoundChannel(event.target).removeEventListener(event.type, onComplete);
    playSound();
}
 //end loop

This doesn't report any errors; however it doesn't play any sounds either. Am I missing something? Do I need to import something to the .fla before it can register the sound?

Thank you for any help

How to reference a stage instance of a MovieClip from a non-document Class without causing Error 1120?

I have a basic AS3 question that has to do with the relationship between object on the stage and objects that are created and controlled by AS3 script. This question has already been addressed tons of times, and I've researched it for hours, but I found drastically different answers, many which were really complicated. I'm looking for the simplest, most general solution to this issue that is humanly (or perhaps I should say computerly) possible.

I want to be able reference an instance of an object on the stage inside a class that is not the main document class. Before I try to explain in my own terms, it might be better to view one of these posts, which cover the exact topic I'm confused about. If any of you understand the issue, and understand the solutions to one of these posts, perhaps you could translate one of the correct answers into n00banese for me. Rather than just focusing on how they did it, you could explain WHY it was necessary to do it that. I would be very thankful if someone could do that much, and if you can it is not necessary to read any further into this post.

AS3 - Access MovieClip from stage within a class

How do I access a MovieClip on the stage from the Document Class?

AS3 Modify stage Objects from a class

how do I make non-document-class classes 'aware' of stage components in Flash AS3?

Accessing ActionScript3 Nested Movie Clips from Class

Since it's highly possible that all of the above-mentioned situations are too complicated for me, I recreated the problem in the simplest, most general way possible in hopes that it would be easier to explain in this case.

I have a MovieClip on the stage with instance name scene_mc. scene_mc does nothing except separate one scene from another. It's linked to a .as file named Scene. Nested inside scene_mc there is a movieclip called thing_mc, linked to .as file Thing. I want to move thing_mc across the scene. I could easily do this by changing its coordinates in the main document class, something like this:

thing_mc.x = thing_mc.x + 100;

But since thing_mc is nested inside of scene_mc, I would like to control thing_mc's position inside the SCENE class so that the coordinates are relevant to other nested symbols in this class. And because in more complicated projects, it just makes sense to control a nested symbol in the code of its parent. So inside Scene.as, I might create this method:

public function moveThing() {
    thing_mc.x = thing_mc.x + 200;
 }

This causes this error: "1120: Access of undefined property thing_mc."

Error 1120 happens any time one tries to reference a stage instance of a symbol a .as file that is not the main document class.

So to reiterate my question, how can I let the Scene class know what thing_mc is? Or how can I let any class know what any stage instance is? How do you reference a stage instance of an object through a non-document class?

Oh! This might be helpful. The Actioscript 3.0 docs say this- Note: Children instances placed on the Stage in the Flash authoring tool cannot be accessed by code from within the constructor of a parent instance since they have not been created at that point in code execution. Before accessing the child, the parent must instead either create the child instance by code or delay access to a callback function that listens for the child to dispatch its Event.ADDED_TO_STAGE event.

So I mean, really I get why what I'm trying to do would cause an error, but I still don't get how to work around it.

Anyone who actually read this far into my gibberish, thank you. You are a kind and patient soul, haha. This issue is really consuming me so any attempt to help me understand the theory of how this works would be IMMENSELY appreciated. :D

lundi 23 mai 2016

How To Integrate SCORM 2.4 With AS3?

I have a project which demands integration of AS3 learning game and a LMS...

Right now I've been using this AS3 class from pipwerks.com but i was not able to get access to further integration like a certain activity and grading... (cmi.objectives)

if someone familiar with this class - there is a way to call in the cmi.objectives?

And for those who develop Flash games with SCORM integration -

how can i achieve the best integration?

do you familiar with better ways to combine SCORM and AS3?

I know there is JS classes as well - but how can i use them with AS3?

Thanks! :)

ActionScript 3.0 Dynamic Text disappearing with button event

So, I am having an issue with ActionScript 3.0. I double checked, and ensured that there is nothing missing. However, I am coming up with an interesting result.

I have a dynamic text, which has an instance of varMoney. Also have a button instance called btnTen_percent.

When, I click the button; it should update the text saying something else. Instead it simply disappear.

public function startShop():void {
  btnTen_percent.addEventListener(MouseEvent.CLICK, tenPercent);
}

private function tenPercent(e:MouseEvent):void {
  trace("10 percent");
  varMoney.text = "1000";
}

So I was wondering, where did it went wrong?

AS3 Seperating Arrays for different items

Hello I have scratched my head about this for 2 hours now, I can't figure it out for the life of me....

I have a function that creates a new value inside an associative array.

var array:Array = new Array(new Array());
var i : int = 0;

 function personVelgLand(evt:MouseEvent)
{

for(i = 0; i < personListe.dataProvider.length; i++)
{

  if(txtPersonVelg.text == personListe.dataProvider.getItemAt(i).label)
  {


    personListe.dataProvider.getItemAt(i).reise = array;

    personListe.dataProvider.getItemAt(i).reise.push(landListe.selectedItem.land);

   }


}

}

The problem is that every new value that are supposed to be pushed into the array and then into the different items are applied to all items in the list when the function runs. How do I make the values seperate for each item?

AS3 Error drag and drop multiple draggable object to multiple target

I want to make the game drag and drop to create multiple draggable objects and it can dragged to multiple targets. But I encountered an error when I drag to the first object that I choose to certain target object is not dragged to the target and then I drag it to another target then succeed. I wanted to fix it. And if you can fix it when the object is dragged to the target and then want to be replaced by another object then the dragged object will be replaced and returned to its original position.

This is a overview the program

enter image description here

And this is the source codes that I use

var xPos:int;
var yPos:int;
var poin:int = 0;
var namaobj1:String;
var namaobj2:String;

addListeners(membaca, menulis, berenang, sepakbola, melukis, memasak, menari, bercocoktanam, beladiri, bermainmusik);

proses.addEventListener(MouseEvent.CLICK,proses1);


function getPosition(target:Object):void
{
    xPos = target.x;
    yPos = target.y;
}

function dragObject(e:MouseEvent):void
{
    getPosition(e.target);

    e.target.startDrag(true);
}

function stopDragObject(e:MouseEvent):void
{
    if (e.target.hitTestObject(getChildByName("target2")))
    {
        e.target.x = getChildByName("target2").x;
        e.target.y = getChildByName("target2").y;
        namaobj2 = e.target.name;
    }

    else if (e.target.hitTestObject(getChildByName("target1")))
    {
        e.target.x = getChildByName("target1").x;
        e.target.y = getChildByName("target1").y;
        namaobj1 = e.target.name;
    }
    else
    {
        e.target.x = xPos;
        e.target.y = yPos;
    }


    pil1.text = namaobj1;
    pil2.text = namaobj2;


    e.target.stopDrag();

}

function addListeners(... objects):void
{
    for (var i:int = 0; i < objects.length; i++)
    {
        objects[i].addEventListener(MouseEvent.MOUSE_DOWN, dragObject);
        objects[i].addEventListener(MouseEvent.MOUSE_UP, stopDragObject);
    }
}

I'm using draggable objects by putting addListener function.

I also include his .fla can be downloaded here ( TEST.FLA ) rather you can more easily apply fixed codes

AS3 referencing a list item which has no name

list.addItem({label:"a"});

When you add an object to the list like this, how do you reference to it later without using a listener for the list and then going

list.selectedItem

Are list items not indexed like arrays? I would want to do something like this

   trace(list.item[0].label);

And have it return "a" Is this not possible with lists?

How can i update the already exsistant array that is outputed in the textArea with info given by the user?

I have 2 seperate arrays declared, where the corresponding index of each array is "information" about a person.

var alderArr: Array = [45, 34, 18, 12, 27];
var navnArr: Array = ["N. Linjesæter", "P. Kurverud", "O. Sirkelstad", "J. Rektangelsen", "M. Ellipsen"];

Then i also have 2 different input fields where the user can input information that will get added to the array when the button btnLeggTill is pressed. And the arrays seem to update based on the trace(alderArr + "\n" + navnArr)

btnLeggTil.addEventListener(MouseEvent.CLICK, leggTil);
function leggTil(evt:MouseEvent) {

    var nyttNavn: String = txtNavn.text;
    var nyAlder: int = int(txtAlder.text);
    //trace(nyttNavn + nyAlder);                            Debug
    alderArr.push(nyAlder);
    navnArr.push(nyttNavn);
    trace(alderArr + "\n" + navnArr);                                   
}//leggTil()

for (var i:int = 0; i < alderArr.length; i++) {

    textArea.text += navnArr[i] + ", Alder: " + alderArr[i] + "\n";
}//for

But the information does not seem to update in the textArea. This is basically what I want to accomplish. I want to make it so that when the user inputs new information and new things are added in the array, the textArea will also be updated so it displays this information to the user.

ENTER key going to next scene. Adobe animate, actionscript 3

So I have a quiz on frame one of scene one. When the user gets a certain number of questions right it goes to scene two.

However the problem is if the user presses enter it skips the whole quiz an goes straight to scene two.

Any ideas on how to disable this? Flash Cc had a disable keyboard shortcuts under the control panel but it's been taken out in animate..

Also, I have a eventlistener on the enter key but it's still ignoring it and skipping the scene =(

How do I make sure that the file is closed after open in Actionscript 3?

How do I make sure that the open file is closed after use?

I am using the following codes to open and write files:

        var mFile:File = new File ();
        var actvityDirectoryXMLFile:File = mFile.resolvePath ( filePath );
        var stream:FileStream = new FileStream ();

        stream.addEventListener ( Event.COMPLETE , onFileWriteComplete );
        stream.open ( actvityDirectoryXMLFile , FileMode.WRITE );
        stream.writeUTFBytes ( xml.toXMLString ());
        stream.close ();
        stream.openAsync ( actvityDirectoryXMLFile , FileMode.READ );
        mFile = null;
        actvityDirectoryXMLFile = null; 

My problem is that if i am saving my lessons first time then it is saving the lessons perfectly but after modification if i am saving the same lessons again then I am getting the following Error:

"Error: Error #3013: File or directory is in use. at flash.filesystem"

I don't know why it is showing like this as I have already written stream.close (); after file write.

So anybody have an idea why it is showing like this or how to solve this problem.

dimanche 22 mai 2016

How do you access a stage object from a non-document AS class?

I'm a complete n00b to AS3 and coding in general, and StackOverflow has been an amazing learning resource. Most questions I've had were answered by reading other posts, but even though this question has already been addressed tons of times, I'm still not understanding how to do it. Since it's easier to understand with an example, I'll explain what I'm trying to do with my code, but honestly if you can answer the question with a more general example that would be just as good if not better.

I have a symbol called Star, and since I want to control a large group of stars I have a .as file called StarArray. When I first was experimenting with this I had a blank symbol on the stage called container_mc. In the StarArray class, added all the stars to container_mc like so:

for (var i:int = 0; i < 50; i++) {

            mc = new star();

            mc.x = ((Math.random() - .5) * 100) ;   
            mc.y = ((Math.random() - .5)* 50);
            container_mc.addChild(mc);
}

This worked fine.

Now I'm trying to be more organized and nest the container_mc object inside the symbol that contains this whole scene, called parkScene_mc. I tried doing the same for loop example ending with parkScene_mc.container_mc.addChild(mc), but it says that parkScene_mc and container_mc are undefined, which isn't surprising. I understand why you would need to store the values of the stage objects in variables within the class, but I just can't figure out how.

Even if my code doesn't make sense, in general I really just want to know how I can access a stage object from a non-document AS3 class. There are upwards of 50 questions similar to mine on this site, but they all seem to have drastically different answers. Can someone explain to me in the simplest way possible what is the best way to do this? Keep in mind I'm new to coding so you may need to explain things that would be common sense to a decent programmer. Feel free to reference one of the posts below and maybe dumb down the answer for me, haha. Thanks in advance.

Posts with similar questions and answers I don't understand:

How do I access a MovieClip on the stage from the Document Class?

AS3 Modify stage Objects from a class

how do I make non-document-class classes 'aware' of stage components in Flash AS3?

ActionScript Error #2035: URL Not Found

I am receiving an error to suggest that my URL is not found. I am running the below simple script from Flash Builder. As I understand the application launches from bin-debug directory within the main project folder.

I have a image folder also within the main project folder yet it will not find the image. It works when I type the full directory.

The code I have is:

package
{
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.net.URLRequest;

    [SWF(width="550", height="400", backgroundColor="#FFFFFF", frameRate="60")]

    public class Kitties extends Sprite
    {
        //Declare the variables for the background.
        public var backgroundURL: URLRequest;
        public var backgroundLoader: Loader;
        public var background: Sprite;

        public function Kitties()
        {
            backgroundURL = new URLRequest();
            backgroundLoader = new Loader();
            background = new Sprite();

            backgroundURL.url = "..\\images\\background.png";
            backgroundLoader.load(backgroundURL);
            background.addChild(backgroundLoader);
            stage.addChild(background);
        }
    }
}

I understand I need to add an event listener to capture this error but for now it's not necessary as i know the file exists. Has anyone experienced this before?

Thank you.

Saving large image with adobe air freezes

I am trying to save large image created by drawing a dynamically created movieclip with bitmapdata draw function.
and i am using some lib to encode the bitmapdata with chosen dpi.
everything works fine but the app freezes for like a minute to create one image with size 1.3 MB.
so i am wondering if there is a way to fix that.

var mc:MovieClip = new MovieClip();
var mat1:Matrix= new Matrix();
mat1.scale(300/72,300/72);
var bitData:BitmapData = new BitmapData(mc.width * (300/72),mc.height *(300/72));
bitData.draw(mc,mat1);
var encoder:JPEGEncoder = new JPEGEncoder();
var imgData:ByteArray = encoder.encode(bitData,300);
file = new File(File.applicationDirectory.resolvePath(savePath.url +"/Image 1.jpg").nativePath);
fileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes(bitData);
fileStream.close(); 

How to detect position of the click?

I want to make an object move to the position of a click how can i do that?

I only want to know how to detect the x-coordinates and y-coordinates of the click ?

Inserting Data Into a 2D Array Actionscript 3

Basically I'm trying to insert a number into a 2D array like this:

arrayName[X][Y] = 4;

but I get an error that says:

TypeError: Error #1010: A term is undefined and has no properties.

so how do I fix this or do it properly?

Flash with PHP Integration: Variable error

I'm starting to learn how to integrate flash with php files and I'm having trouble with the retrieving of variables.

Here's my AS3 code:

var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, varsLoaded);
loader.load(new URLRequest("http://localhost/flash.php")); 

function varsLoaded (event:Event):void {
    trace(loader.data); // sample text

}

And my PHP file goes something like this:

<?php

    $txt = "sample text";
    print "myVar = $txt";

?>

I changed the value of myVar but the changed value does not apply. Please help.

ActionScript3 How to detect object's position while its moving

I am trying to detect objects position while its moving but I cant

I tried this

stage.addEventListener(Event.ENTER_FRAME,traceposition)
function traceposition(e:Event):void
{
trace(object.x)
}

It only gives it after it stops moving ,any help?

samedi 21 mai 2016

Why (root as MovieClip).this["mc"+i] doesnt work?

How can I control 3 movie clips from another mc dynamically? My 3 clips are mc1, mc2 and mc3. What is wrong with the codes given below?

for(i=1;i<=3;i++){
(root as MovieClip).this["mc"+i];
}

Function does not return a value (Error 1170; ActionScript 3.0)

I'm currently trying to create a system where a function will roll for a new number everytime it is called (So I can then use that output to reset the scene with a new number (Number calls an array)). Currently this is my set up;

function randomNum():Number{
return this(Math.round(Math.random()*range) + minLimit);
};

The above is the function I have made to calculate new numbers on the fly. All relevant variables below;

var output = randomNum();

function randomFruit():String{
return fruits[output];
}

So pretty much the random number function rolls providing a new number for the output variable, which is then used to pull a new item out of an array. The issue I'm getting is that the random number function isn't returning any values, thus causing errors. Does anyone know how to fix this? I'm uncertain if this is the best way to reroll a new item out of an array but it's the easiest implementation I can think of.

Cheers for any assistance, as I've reached my wits end trying numerous fixes to no avail :/

What caused Flash and Actionscript to become irrelevant?

At first glance this question may seem like I'm looking for opinions or a discussion, but hear me out. While I'm sure everyone has their own opinion of which tools are best to use, there have got to be some factual reasons why Flash's popularity faded away. I'm sure there were certain events and inventions that caused people to prefer other tools, and I'm dying to know what those events are. So I am looking for answers that are based on facts and events. All I can gather from the research I've done and the projects I've seen is that Flash used to be really popular for creating interactive media or cartoon-like movies, but now it's not.

The background story to this question is that over the past few months I've been creating a project with Adobe Animate and Actionscript for a college class. It's been fun and I find that Animate is extremely useful. I would like to think that the skills I've learned will be useful in the future, but I've heard from several different people that Flash is pretty much irrelevant now and I can't figure out why.

I know that front end developers are using Javascript and HTML/CSS for most things, and I do understand some of the advantages. Javascript programs seem to have more open-source availability, and of course no one wants to pay a subscription for Adobe products forever. But what I don't get is what replaced the visual aspect of the "stage". Something as simple as drawing a circle could become hard really quick, or tedious at the least, if you're just using code alone. And if you draw two or more objects, you have to worry about their relative positions. Flash makes that super simple by allowing you to just drag them to where they need to be. But once again I imagine it would be really boring to have to use trial and error to position things solely with code.

So are the Javascript coders using something similar to Flash for their animations that I'm just not aware of, or are they really just using code alone? If they are just using code, WHY would they give up the stage aspect of design?

Flash policy request C

I am trying to make a server for a flash game in C, however I am having problems with the "flash policy" part.

Connection send code + flash policy rule: send(connfd, "\nhttp://www.w3.org/2001/XMLSchema-instance\” xsi:noNamespaceSchemaLocation=\”http://ift.tt/27LMdA5\”>\n\n\n\n \0", "\0",0);

Server respond is still " ".

Thank you

AS3 printing the lowest value to a dynamic textfield

var a:Object =({label:"2008",n:8560,i:15909});

Lets say I have five objects similar to this in a list component. Is there possible to have a function that prints out the label of the item which has the lowest value n ? What would I have to do to accomplish this?

How to make a picture smaller while swiping up?

I am new to action script , I want a picture to be smaller as I swipe my finger upwards , how do i do it?

Thanks

ActionScript classes reference

I have a class Square and a class Circle.

This my class Circle:

public class Circle extends MovieClip
    {
        var growthRate:Number = 2;

        public function Circle() 
        {

            addEventListener(Event.ENTER_FRAME, grow);  

        }
        function grow(e :Event):void
            {
                e.target.width +=growthRate;
                e.target.height +=growthRate;
            }

    }

I need to stop growing the circle inside a function from Shape.

public function Square() {
            buttonMode = true;
            addEventListener(MouseEvent.MOUSE_DOWN, down);

        }

        protected function down ( event: MouseEvent):void 
        {
        //here i need to stop the circle
        }

I don't know how to make a relation with the Circle class in order to stop the circle growing.

Thank you in advance.

AIR AS3 - Create image file using movieclip

I'm wondering if there's any way of creating a file in AIR that's an "image" of a movieclip. Essentially what I want to do is have multiple existing images loaded into the one movieclip in a grid then export then as a single image.

vendredi 20 mai 2016

how to load a videoclip by its instance name within a swf into a web page

Suppose I have a SWF file, its library structure is: library structure

and for the 3 MovieClips in the library, there are 3 different instance names: instance names

My question is, I want to add this SWF file to a web page, BUT I only want to display a certain MovieClip, for example "step3". How do I achieve this?

AddChild to use external SWF has disabled my buttons I had on original Flash file

I have a Flash file (a website header with 5 buttons for 5 links to webpages). On my actions layer, I added an external SWF file using the addChild object.

Note that I have very basic knowledge of ActionScript and I had to take some help from Google to setup above script.

The external SWF I have brought in using adChild code is working as an overlay on top of my original flash animation but all the buttons I have on original Flash file as website links have now become disabled. Even the mouseOver effects I applied to those 5 buttons are not responding. Below is my AS3 code:

    import flash.net.navigateToURL;
    import flash.net.URLRequest;


    stop();

    var swfRequest:URLRequest = new URLRequest("movie/txtOverlay.swf");
    var swfLoader:Loader = new Loader();

    swfLoader.load(swfRequest);
    addChild(swfLoader);

    button_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
    function fl_MouseClickHandler(event:MouseEvent):void
    {
    navigateToURL(new URLRequest("http://ift.tt/1RdUK2E"),  "_self");
    }

For the sake of brevity, I have placed just one button's code but you get the idea. Any solution to avoid this? Thanks ... Syed

Is it possible to put a Class linked to a document (aka Document Class) into a RSL and still have it as Document Class?

Firstly, my environment. My question is if it's possible to do so using Flash Professional and not Flex, FlashBuilder or the like (I don't have those environments at the moment).


Here is the thing: we have several .fla files with a Document Class set. The .as file with the class is shared with all those .fla files, so all them have this same class set as their Document Class. The point is that because of that the Class is compiled into each generated .swf files, and as result any changes made to the Class would require all the .fla files to be recompiled.

After some research I found out about RSLs. But I'd like to know if it's possible to have the class as RSL while also having it as Document Class for each file? It would ease stuff because in case a change needs to be done in the class we wouldn't need to recompile each file, or regenerate each .swf files.

Aditionally, if it's possible, how could I implement a RSL through Flash Professional? All the documentation I have found shows that through Flex and others.

Please let me know if I wasn't clear enough.

How to add vertical scroll bars on textarea in Actionscript 3?

I wants to add vertical scroll bar in textarea spark component, i.e I want to show maximum 5 lines in textarea if text line will more than 5 then vertical scroll bar will automatically add and if i will reduce the text line then vertical scroll bar will automatically disappear.

My textarea code is :

<s:TextArea id="txtArea" width="{this.width}" height="3" borderVisible="false" focusAlpha="0.01" 
            selectionHighlighting="always" styleName="TextBox"
            needsSoftKeyboard="true" focusRect="false" direction="{textBoxDirction}" buttonMode="true" useHandCursor="true" mouseChildren="true"/>

I also tried to use verticalScrollPolicy = "on" and "off" but it is also not working.

So if anybody have an idea how to add vertical scroll bar in textarea please help me to solve this problem.

AS3- play/pause/next/back/replay

current im a fresh AS3 coder ,i have 10 external swf on 1 stage ,does anyway can control it?i have been try pause/play but only able stop 1 page,sound cant pause... it has been 3 days for this..

code

loading external swf files from different domain in localhost with flash CS5

I have been struggling with this problem for days and have searched the internet but got no solution. I am using Xampp on Windows 7 with Flash CS5
I have 2 swf located in different domain at localhost
- localhost/mading/flash/NewMading.swf
- localhost/kamus/flash/NewKamus.swf
Both these files read data from mysql server
Both swf are working fine
When I want to load NewKamus.swf from NewMading.swf I got this error

SecurityError: Error #2142: Security sandbox violation: local SWF files cannot use the LoaderContext.securityDomain property.
file:///C|/xampp/htdocs/mading/flash/NewMading.swf was attempting to load http://localhost/kamus/flash/NewKamus.swf.
at flash.display::Loader/_load()  
at flash.display::Loader/load()  
at NewMading_fla::MainTimeline/GetKamus()[NewMading_fla.MainTimeline::frame1:512]  
at NewMading_fla::MainTimeline/KlikKamus()[NewMading_fla.MainTimeline::frame1:956]

Here is my crossdomain.xml

<?xml version="1.0" ?>
<cross-domain-policy>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

Here is my actionscript code in the NewMading.swf (I did not copy all my code because it will be to long, just I think necessary).

import flash.system.Security;
import flash.system.SecurityDomain;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;

Security.allowDomain("*");
Security.loadPolicyFile('localhost/mading/crossdomain.xml');

function GetKamus(url:String):void {
  var swfLoaderKamus:Loader = new Loader(); 
  var LC:LoaderContext = new LoaderContext(); 

  swfLoaderKamus.contentLoaderInfo.addEventListener(Event.COMPLETE,  GetKamusComplete);

  LC.securityDomain = SecurityDomain.currentDomain; 
  LC.applicationDomain = ApplicationDomain.currentDomain; 
  LC.checkPolicyFile = true;

  swfLoaderKamus.load(new URLRequest(url),LC);

  function GetKamusComplete(e:Event):void {                         
    addChildAt(swfLoaderKamus, 0);  
    swfLoaderKamus.contentLoaderInfo.removeEventListener(Event.COMPLETE, GetKamusComplete);
  } 
}

function KlikKamus(e:MouseEvent):void {         
    GetKamus('http://localhost/kamus/flash/NewKamus.swf');
}

When the button associated with KlikKamus function is clicked I got the error. Any ideas?

jeudi 19 mai 2016

AS3 Jumping (flying) issue

Ive searched around a bit but I couldnt find an answer I can work with.I probably didnt look hard enough. I have been out of school for about a year now and I came across a flash game we made in class. I was trying to fix some errors on it that Ive made to make it function properly. The issues Ive come across are a Jumping issue : The character can endlessly jump as if it is flying through the sky. The next error is the attack graphic doesnt play unless the player is in the sky. Im rusty with the coding and I am looking to get back into as3 and using the flash program. I have a "player.as" file, I will paste its code below. Any help is appreciated, thanks in advance.

package  {

import flash.display.MovieClip;
import CollisionObject;
import flash.events.Event;
import flash.events.TimerEvent; 
import flash.utils.Timer;

public class Player extends CollisionObject {
    private var xMovement:Number;
    public var isAttacking:Boolean;
    private var attackTimer:Timer = new Timer (500, 1);

    public function Player() {
        // constructor code
        trace("I am the player");
        xMovement = 0;
        isAttacking:false;

        addEventListener(Event.ENTER_FRAME, enterFrameHandler);
    } // end constructor

    private function enterFrameHandler(event:Event):void{
        this.x += xMovement;
    } //end function

    public function attack() {
        isAttacking = true;
        this.gotoAndStop("attack");
        attackTimer.addEventListener(TimerEvent.TIMER_COMPLETE, doneAttacking);
        attackTimer.start();
    }

    public function startJumping(){
        if (isJumping == false) {
            isJumping == true;
            this.gotoAndStop("jump");
            downwardVelocity = -20; 
        }
    }

    public function doneAttacking  (event:TimerEvent):void{
        isAttacking = false;
        this.gotoAndStop("stop");
    }

    public function moveLeft() : void{
        xMovement =-7;
        this.scaleX = -1;
        this.gotoAndStop("run");
        isRunning = true;
    } //end function

    public function moveRight() : void{
        xMovement =7;
        this.scaleX = 1;
        this.gotoAndStop("run");
        isRunning = true;
    } //end function

    public function standStill() : void{
        xMovement = 0;          
        isRunning = false;
    } //end function

    override public function positionOnLanding(){
        if(isRunning == true){
            this.gotoAndStop("run");
        }else{
            this.gotoAndStop("stop");
        } //end else
    } //end function
} // end class

Is there any way to establish a communication between AS3 script and Apache Derby database directly?

I'm trying to build a flash app that communicates with derby database without any JS, XML or any intermediate stuff. I've read about SQLConnection (adobe reference ) instance but dont quietly get if it's able to do same with derby.

I am quiet familiar with JSON, JAVA EE but newbie to flash development. Help would be really appreciated.

If that's not possible I'd love to try JSON Post requests to servlet ( which whill ofcourse get the stuff from db ).

how to embed external xml with fla & publish them as a single swf file?

so recently i finished making a quiz with flash CS6 that loads questions from an external XML file ,but now i need to merge the .fla file with the external xml & publish them as a single swf file & as simple as it sounds i couldn't figure the right way to do this .

here is my xml loader:

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(new URLRequest("quiz.xml"));

im a total beginner when it comes to using xml , so any help would be greatly appreciated.

Reading special charactors using XMLSocket in Actionscript 3.0

Using the XMLSocket class in as3 i am trying to read the string that include special characters (including chinese symbols) sent by a .NET server that uses the Socket class in c# for communication. The log shows the data properly . But when i get it in as3, all the special characters are replaced by '?'. I thought it would be a font issue. But tried with embedding the fonts and got the same result. If i read a file having special characters using URLLoader, then everything is proper. But when i tried to read the data sent by the .net server using the flash XMLSocket class the special characters are replaced. Is there any encoding we need to set in .net Socket class or somewhere or can this be solved from the client side(flash as3) itself?

thanks in advance

mercredi 18 mai 2016

Link for iOS app rating

I've been trying to direct users to the app store (iTunes) to rate my app. I can't get the right link. Users say that when they click the button, nothing happens.

This is the current link I'm using:

tms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXX

And in my code, which is for Adobe AIR, this is the line:

navigateToURL(new URLRequest("tms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=XXXXX"));

(Of course XXXXX is replaced with my App ID).

Appreciate any help. Thanks.

Looping for events in actionscript 3, only get last number

So I want to code faster by making array of all button that I have, and also make array of function which index numbers are connected to the array of each buttons.

For example, buttons[0], handler events for hover is button_over_funcs[0] and for out is button_out_funcs[0].

To make it clearer (since english is not my first language), take a look at my code:

var buttons:Array = [playbtn, tutorialbtn];
var button_over_funcs:Array = new Array();
var button_out_funcs:Array = new Array();

var i = 0;
for each(var j in buttons){
    j.buttonMode = true;

    button_over_funcs.push(function(e:MouseEvent){
        j.gotoAndPlay("hover");
    });
    button_out_funcs.push(function(e:MouseEvent){
        j.gotoAndPlay("out");
    });


    j.addEventListener(MouseEvent.ROLL_OVER, button_over_funcs[i]);
    j.addEventListener(MouseEvent.ROLL_OUT, button_out_funcs[i]);
    i++;
}

but the j will always refer to tutorialbtn, regardless which button I hover/out. I tried for-in as well

var buttons:Array = [playbtn, tutorialbtn];
var button_over_funcs:Array = new Array();
var button_out_funcs:Array = new Array();

for(var j in buttons){
    buttons[j].buttonMode = true;

    button_over_funcs.push(function(e:MouseEvent){
        buttons[j].gotoAndPlay("hover");
    });
    button_out_funcs.push(function(e:MouseEvent){
        buttons[j].gotoAndPlay("out");
    });


    buttons[j].addEventListener(MouseEvent.ROLL_OVER, button_over_funcs[j]);
    buttons[j].addEventListener(MouseEvent.ROLL_OUT, button_out_funcs[j]);
}

Both seems the same. It seems like actionscript always refers to the last value of j instead of assigning it. Do you have any idea on how to make this as I expected? Is it impossible to make this quicker and not assigning the button to do same exact stuff?

AS3 How to make sprite face direction it is moving

So I have two movieclips: mcMain which is my character that faces the right and I have mcMainLeft which is my character that is facing the left. I tried to implement code so that when the left arrow is pressed, mcMainLeft is visible and is moving to the left. Same thing for mcMain and to the right. So what ends up happening is that when I move left, it moves left and the character faces left, but then I'll click the right arrow and move it right and it won't move my current character at the current location, it'll start from a different position. I'm not sure what the deal is.

Here is my code:

//These variables will note which keys are down
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 7;
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 15;
//the current speed of the jump;
var jumpSpeed:Number = 0;

//set coordinates of pacman left and right
mcMain.x = 270;
mcMain.y = 370;
mcMainLeft.x = 270;
mcMainLeft.y = 370;

//make pacman left invisible on startup
mcMainLeft.visible = false;

//move character function
mcMain.addEventListener(Event.ENTER_FRAME, moveChar);
mcMainLeft.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
    //if certain keys are down, then move the character
    if(leftKeyDown ){
        mcMainLeft.x -= mainSpeed;
    }
    if(rightKeyDown){
        mcMain.x += mainSpeed;
    }
    if(upKeyDown || mainJumping){
        mainJump();
    }
}

//listening for the keystrokes
//this listener will listen for down keystrokes
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void{
    //making the booleans true based on the keycode
    //WASD Keys or arrow keys
    if(event.keyCode == 37 || event.keyCode == 65){
        leftKeyDown = true;
        mcMain.visible = false;
        mcMainLeft.visible = true;
    }
    if(event.keyCode == 38 || event.keyCode == 87){
        upKeyDown = true;
    }
    if(event.keyCode == 39 || event.keyCode == 68){
        rightKeyDown = true;
        mcMain.visible = true;
        mcMainLeft.visible = false;
    }
    if(event.keyCode == 40 || event.keyCode == 83){
        downKeyDown = true;
    }
}
//this listener will listen for keys being released
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void{
    //making the booleans false based on the keycode
    if(event.keyCode == 37 || event.keyCode == 65){
        leftKeyDown = false;
    }
    if(event.keyCode == 38 || event.keyCode == 87){
        upKeyDown = false;
    }
    if(event.keyCode == 39 || event.keyCode == 68){
        rightKeyDown = false;
    }
    if(event.keyCode == 40 || event.keyCode == 83){
        downKeyDown = false;
    }
}

//jumping function
function mainJump():void{
    //if main isn't already jumping
    if(!mainJumping){
        //then start jumping
        mainJumping = true;
        jumpSpeed = jumpSpeedLimit*-1;
        mcMain.y += jumpSpeed;
        mcMainLeft.y += jumpSpeed;
    } else {
        //then continue jumping if already in the air
        if(jumpSpeed < 0){
            jumpSpeed *= 1 - jumpSpeedLimit/75;
            if(jumpSpeed > -jumpSpeedLimit/5){
                jumpSpeed *= -1;
            }
        }
        if(jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit){
            jumpSpeed *= 1 + jumpSpeedLimit/50;
        }
        mcMain.y += jumpSpeed;
        mcMainLeft.y += jumpSpeed;
        //if main hits the floor, then stop jumping
        //of course, we'll change this once we create the level
        if(mcMain.y || mcMainLeft.y >= stage.stageHeight - mcMain.height || mcMainLeft.height){
            mainJumping = false;
            mcMain.y = stage.stageHeight - mcMain.height;
            mcMainLeft.y = stage.stageHeight - mcMainLeft.height;
        }
    }
}

Flash An Error- 1013: The private attribute may be used only on class property definitions

I'm trying to make a timer countdown, I believe I have all the pieces there its just keeps giving me this error when whenever I test it.

Any idea what's going on?

package 

{
    import flash.display.MovieClip;
    import flash.events.TimerEvent;
    import flash.utils.Timer;

    public class MainTimer extends MovieClip {
        private var currentMin:int;
        private var currentSec:int;

        private var oneSecondTimer:Timer = new Timer (1000,1);
        public var timeHasStopped:Boolean=false;

        public function MainTimer() {
        // constructor code
            trace("the main timer is here");
            currentMin = 2;
            currentSec = 5;

            minBox.text = String(currentMin);

            if(currentSec < 10)
            {
                secBox.text = "0" + String(currentSec);
            }
            else {
                secBox.text = String(currentSec);
            }

            oneSecondTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
            oneSecondTimer.start();

            private function onTimerComplete(event:TimerEvent):void {
                currentSec = currentSec -1;
                if(currentSec <0) 
                    {
                        currentSec =59;
                        currentMin -=1;
                    } //end if
                if(currentMin < 0) {
                        currentMin =0;
                        currentSec =0;
                        timerHasStopped = true;
                }
                else 
                    {
                        oneSecondTimer.start();
                    }
                minBox.text =String(currentMin);
                secBox.text =String(currentSec);

                if(currentSec <10) 
                    {
                        secBox.text = "0" + String(currentSec);
                    }
            }
    } // Ends Function

} // Ends Class

} // Ends Package

Why won't my script remove files from folder larger than 1 mb?

I am writing a batch file to remove files larger than 1 MB from a folder located on my desktop. But when running the script, it removes random items and not the ones over 1mb. Is my script wrote improperly?

@ECHO OFF

DEL /S /Q "C:\Users\TSwanson\Desktop\Test Folder*." FOR /R "C:\Users\TSwanson\Desktop\Test Folder" %%F IN (.*) DO ( IF "%%~zF" GEQ "10240" (ECHO DEL /F %%F)) pause > nul EXIT /B /0

Unxpected result of Number(Number) + Number(String)

I can't figure out why is it so:

var a:String = "0.07";
var b:Number = 0.08;
trace( Number(a) + Number(b) ); // 0.15000000000000002

, but when using tenths, results are ok:

var a:String = "0.7";
var b:Number = 0.8;
trace( Number(a) + Number(b) ); // 1.5

Actionscript 3, walk cycle loop during tween motion

I have a MC character, inside of it there's a walk cycle frame by frame animation

My character move on the stage with a tween (used tweenLite from GreenSock) wherever you click with the mouse.

I want the walk cycle loops till the end of the tween, actually it iterates only one time, any advice?

how to add frames to timeline dynamically?

hate to ask but I actually need to dynamically add 240 frames to a pure AS3 project and then a stop frame on the last frame.

Yes we're back in 2009.

Why?

Because the dynamic, class driven PureAS3 application I've build (swf) is being delivered to a different media owner who's inhouse system (I kid you not) checks all Flash for 10 seconds of frames(hence 240) AND checks for a 'stop();'.

Any help greatly received - I'm assuming this is possible but drawing a blank online - mainly lots of people (rightly so) advising again using the timeline.

Rich

AS3 Display random word from array onto stage

I have an array of words in my code. What I'm hoping to do is display, at random, one word from the array onto the stage. How is this achievable?

mardi 17 mai 2016

AS3: Why does this child MovieClip have no size?

I have a parent MovieClip that fills the entire screen at 1920x1080; lets call it Screen. I'm then adding a child MovieClip to it like the following:

var mcLayout:MovieClip = new MovieClip();
mcLayout.width = 512;
mcLayout.height = 512;
trace("-------mcLayout: " + mcLayout.width + " " + mcLayout.height);

mcLayout.graphics.beginFill(0x222222, 0.75);
mcLayout.graphics.drawRect(0, 0, mcLayout.width, mcLayout.height);

Screen.addChild(mcLayout);
trace("-------mcLayout: " + mcLayout.width + " " + mcLayout.height);

The trace statement always reports that the size of mcLayout is 0 0. Why would that be? This makes absolutely no sense to me. I'm clearly specifying the size and filling it with something (a rectangle) so I see no reason as to why it would fail to maintain its size.

I've also tried changing it to a Sprite and that has the same problem. There's obviously something fundamental I'm missing here, but I can't figure it out.