dimanche 31 mai 2015

Timer flash to show something at the right time

I want to make a timer that will show text at my panelText (dynamic text box) at specific time, actually I have a video that I want to have subtitles, and I want to use timer, my video is 3 minutes and 37 second long, and I have script that I want to show at some time, example at 1 minute 0 seconds it will show the text "hello, this is my video to learn about solar system" in my panelText, and at 2 minute I want to show text "There are 8 planets in our solar system", something like that. For information, I'm using flvPlayback to play the video and load the external video.

An example from my code:

var myTimer:Timer = new Timer(217000);
var time = 0;
myTimer.start()
myTimer.addEventListener(TimerEvent.TIMER,timerHandle);

function timerHandle(event:TimerEvent){
    if(myTimer == 120000)
    {
        panelText.text="There's 8 planets in our solar system";
    }                                                                              

and i got error 1176: Comparison between a value with static type flash.utils:Timer and a possibly unrelated type int. can someone help me?, i'm sorry for my bad english

categorize arrays AS3

I've got this array :

var usersArray:Array = new Array("this is array1 and it's a good array","this is array2", "this is array3", "this is array4", "this is array");
usersArray.push(usersArray.splice(usersArray.indexOf("UserID"), 1));

var companion:String = usersArray[Math.floor(Math.random() * (usersArray.length - 1))];

  trace(companion);

Is it possible to class the array with letter or number as my array could be very long ?

Like

if (companion==A){
trace("this is array 1")
}

Instead of

if (companion=="this is array1 and it's a good array"){
trace("this is array 1")
}

Thanks !

Editing a Sprite variable in a SWF With C#

so i am trying to develop a trainer for a game silly i know but none the less i want to know how to edit a sprite variable with in the Action script of the game through a button and a text

// Action script...

// [Initial MovieClip Action of sprite 2248]
#initclip 12
class gameData
{
    var PLAYERID, PLAYERNAME, LASTMODIFIED, DIFFICULTY, CLEVEL, MONEY, AMMO_TOTAL, POINTS;
    function gameData(_PLAYERNAME)
    {
        var _loc2 = new Date();
        PLAYERID = String(_loc2.getTime());
        PLAYERID = PLAYERID + String(Math.round(Math.random() * 99999));
        PLAYERNAME = _PLAYERNAME;
        LASTMODIFIED = new Date();
        DIFFICULTY = 1;
        CLEVEL = 1;
        MONEY = 0;
        AMMO_TOTAL = [60000, 0, 0, 0, 0, 0];
        POINTS = 0;
    } // End of the function
    static function saveGame(_GAME)
    {
        _global.CGAME.LASTMODIFIED = new Date();
        gameData.saveGames(_global.GAMES);
    } // End of the function
    static function saveGames(_GAMES)
    {
        var _loc1 = SharedObject.getLocal(gameData.GAMEID);
        _loc1.data.GAMES = _GAMES;
        _loc1.flush();
    } // End of the function
    static function newGame(_NAME, _DIFFICULTY)
    {
        var _loc1 = SharedObject.getLocal(gameData.GAMEID);
        var _loc2 = _loc1.data.GAMES;
        if (_loc2 == undefined)
        {
            _loc1.data.GAMES = new Array();
        } // end if
        var _loc3 = new gameData(_name, _DIFFICULTY, _loc2.length);
        _loc1.data.GAMES.push(_loc3);
        _loc1.flush();
    } // End of the function
    static function deleteGame(_INDEX)
    {
        var _loc1 = SharedObject.getLocal(gameData.GAMEID);
        var _loc2 = _loc1.data.GAMES;
        if (_INDEX < 0)
        {
            return;
        } // end if
        if (_INDEX > _loc2.length - 1)
        {
            return;
        } // end if
        _loc2.splice(_INDEX, 1);
        _loc1.flush();
    } // End of the function
    static function getGames()
    {
        var _loc1 = SharedObject.getLocal(gameData.GAMEID);
        var _loc2 = _loc1.data.GAMES;
        if (_loc2 == undefined)
        {
            _loc1.data.GAMES = [];
            _loc1.flush();
        } // end if
        return (_loc1.data.GAMES);
    } // End of the function
    static var GAMEID = "qigames_13DaysNightmare_12";
} // End of Class
#endinitclip

that is the action script sprite i want to edit specifically

var _loc2 = new Date();
        PLAYERID = String(_loc2.getTime());
        PLAYERID = PLAYERID + String(Math.round(Math.random() * 99999));
        PLAYERNAME = _PLAYERNAME;
        LASTMODIFIED = new Date();
        DIFFICULTY = 1;
        CLEVEL = 1;
        MONEY = 0;
        AMMO_TOTAL = [60000, 0, 0, 0, 0, 0];
        POINTS = 0;

i decompiled the swf and can edit the main root or the MainMovie with a button and a text box but i cant seem to figure out of to change the values in the sprite

    ![this is how i edit root variables
  }
Game.SetVariable("_root.EXamplevar", textbox1.Text); 
  {][2]

please help sorry if what i explained was confusing

how to reference a hit test object between .as files [AS3]

i'm trying to make a top down shooter game, and have been following tutorials here: http://ift.tt/1MBdRFj and here: http://ift.tt/1GeLkVF

i've managed to get shooting and movement, but i need to get a hit test object to register when the bullet (defined in its own seperate as class file) and the enemy (also defined in seperate file) come into contact. code below:

Enemy code:

        package 
{
    import flash.display.MovieClip;
    public class Enemy extends MovieClip 
    {
        public function Enemy() 
        {
            x = 100;
            y = -15;            
        }

        public function moveDownABit():void 
        {
            y = y + 3;
        }
    }
}  

Bullet code:

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


    public class Bullet extends MovieClip
    {
        private var stageRef:Stage;
        private var speed:Number = 10;
        private var xVel:Number = 0;
        private var yVel:Number = 0;
        private var rotationInRadians = 0;
        public var enemy:Enemy;



        public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
        {
            this.stageRef = stageRef;
            this.x = X;
            this.y = Y;

            this.rotation = rotationInDegrees;
            this.rotationInRadians = rotationInDegrees * Math.PI / 180;
        }

        public function bullethit():void{
                if (Bullet.hitTestObject(enemy)){
                    gameTimer.stop();
                }

            }

        public function loop():void
        {
            xVel = Math.cos(rotationInRadians) * speed;
            yVel = Math.sin(rotationInRadians) * speed;

            x += xVel;
            y += yVel;

            if(x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
            {
                this.parent.removeChild(this);
            }
        }
    }
}

Main.as document class code:

 package
{
    import flash.display.Stage;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

    public class Main extends MovieClip
    {
        public var player:Player;
        public var bulletList:Array = []; //new array for the bullets
        public var enemy:Enemy;
        public var gameTimer:Timer;

        public function Main():void
        {
            player = new Player(stage, 320, 240);
            stage.addChild(player);

            enemy = new Enemy();
            addChild( enemy );

            gameTimer = new Timer( 25 );
            gameTimer.addEventListener( TimerEvent.TIMER, moveEnemy );
            gameTimer.start();

            stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true);
            stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true); //add an EventListener for the loop
        }

        public function moveEnemy( timerEvent:TimerEvent ):void 
        {
            enemy.moveDownABit();
        }

        public function loop(e:Event):void //create the loop function
        {
            if(bulletList.length > 0) //if there are any bullets in the bullet list
            {
                for(var i:int = bulletList.length-1; i >= 0; i--) //for each one
                {
                    bulletList[i].loop(); //call its loop() function
                }
            }
        }

        public function shootBullet(e:MouseEvent):void
        {
            var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation);
            bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true); //triggers the "bulletRemoved()" function whenever this bullet is removed from the stage
            bulletList.push(bullet); //add this bullet to the bulletList array
            stage.addChild(bullet);
        }

        public function bulletRemoved(e:Event):void
        {
            e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved); //remove the event listener so we don't get any errors
            bulletList.splice(bulletList.indexOf(e.currentTarget),1); //remove this bullet from the bulletList array
        }
    }
}

The right language for the right game

I want to make a simple card game that takes 2 to 4 players. I want to make the game online so that real people can play each other.
I prefer to make this game over a website rather than code an .exe
My question is what's the simplest combination of languages to make the game? Should I try and do it on a website and use Javascript or use ActionScript3 and which one will require less work in order to make 2 different computers play in real time?

How to addChild to a movie clip a movie clip that as bitmap in it

i am trying to create a list in runtime but couldn't make it work.

Here is my code :

var mc:MovieClip = new MovieClip();
addChild(mc);
grpList.source = mc;
for(var i = 0;i<count;i++){
    var img:Bitmap = new Bitmap(new listbitmap(0,0));
    var mvc:MovieClip = new MovieClip();
    mvc.height = img.height;
    mvc.width = img.width;
    mvc.x = 0;
    mvc.y = i * 100;
    mvc.addChild(img);
    mc.addChild(mvc);
    grpItemList.update();
}

I have a scroll pane and inside of it i have a movie clip. In that movie clip i want to list new movie clips that has bitmaps in it. When i try to do it without a new movie clip but adding the image directly, it works like a charm. What am i doing wrong ?

Stop clock on pause button

I have a "clock" counting down the time of the game (from 9 seconds to 0 seconds). I have a button that pauses the game, so I want to freeze de clock and when I click to play, the game continuos from that second that I frozen. But I don't have any idea how to do this! Can you help me please?

this.addEventListener(Event.ENTER_FRAME, updateTimer);

    function updateTimer(e:Event){
        var t:uint = getTimer();
    var dt:uint = 9000 - t;
    var totseconds:uint = Math.floor(dt/1000);
    var minutes:uint = Math.floor(totseconds/60);
    var seconds:uint = Math.floor(totseconds%60);
    var minsWithZ = minutes < 10 ? "0" + minutes : minutes;
    var secsWithZ = seconds < 10 ? "0" + seconds : seconds;
    var time = minsWithZ + ":" + secsWithZ;
    this.tempo_txt.text = time;

}   

pausa.addEventListener(MouseEvent.MOUSE_UP, menuPause);

function menuPause(e:MouseEvent){
    ...somegame code...
    voltar.addEventListener(MouseEvent.MOUSE_UP, play);
}

function play (e:MouseEvent){
    ...some game code

}

Why can't extend DisplayObject then instantiate

The DisplayObject class can be extended but the extended class cannot be instantiated.

Class:

package{
  class Extended extends DisplayObject{

              import flash.display.DisplayObject;


   public function Extended(){
      super()

    }

  }
}

Main timeline:

var e:Extended=new Extended();

addChild(e);

Error:

ArgumentError: Error #2012: Extended$ class cannot be instantiated.

how to wait for a few seconds before starting a function

i want to reload a gun. When R pressed. I want it to wait 3 seconds before loading the gun. Is there a simple way to do this?

example:

if (event.keyCode == Keyboard.R)
        {
            //wait(4 seconds)

                           // start reloading
        }

Take every second element from array in as3

I am making my first as3 game and am taking a username and password field from a MySQL server. The array gets split into each user, but I would also like to split it from username to password. I am then checking if the username and passwords from the database and user input match.

I have programmed everything besides the splitting of username and password, and am happy for any suggestion into the right direction.

Thanks, JacquesCA

how does the "for each in" loop work?

for some reason this code does not work as intended, ive cut out most of my program but, all i think i need to tell you is that i have a tree array. and im trying to make collisions with said trees so i thought that this would work

function collisions(loopEvent:Event):void{
    for each (var a:tree in TreeArray)
    {
        if (brettMc.right1.hitTestObject(a.stump))
    {
        rightcoll = false;
    }
    else
    {
        rightcoll = true;
    }
    if (brettMc.left1.hitTestObject(a.stump))
    {
        leftcoll = false;
    }
    else
    {
        leftcoll = true;
    }
    if (brettMc.up1.hitTestObject(a.stump))
    {
        upcoll = false;
    }
    else
    {
        upcoll = true;
    }
    if (brettMc.down1.hitTestObject(a.stump))
    {
        downcoll = false;
    }
    else
    {
        downcoll = true;
    }
}
}

im pretty sure that the problem is juat that the for each loop is messing up, but im dumb, so that could also be the problem.

Decimal numbers not adding correctly in AS3

In my program, I have a score multiplier variable of type 'Number' When I try to add 0.1 to it, I have a problem. Here is the code:

scoreMultiplier += 0.1;
trace(scoreMultiplier);

scoreMultiplier is originally set to 1, and after the first run through, I correctly get a value of 1.1. However, the second time, the trace shows 1.2000000000000002, and the next time 1.3000000000000003.

There is no other code which modifies scoreMultiplier. This is a problem, first because it is shown on my game screen and goes off the screen, and second because if conditionals where scoreMultiplier==2 for example do not work due to the bizarre fault in the addition.

If anyone knows what's causing this, or at the very least how to truncate the value to 1 decimal place, that would be great.

startAtLogin does not work with captive runtime, Adobe Air for desktop?

I published my Air project with captive runtime and when I set startAtLogin=True, I get a runtime error with code #2014.

Is there any solution for startAtLogin to work with Air app with captive runtime?

samedi 30 mai 2015

AS3 Center Video in StageVideo

I've a brief question that I'm sure some AS3 genius knows.

I'm surprised I haven't seen any other topics on this after 30 minutes of Google-fu, StageVideo seems to be largely silent.

So I've been trying out the StageVideo API in place of traditional Videos for better video playback. This is for a Flash video streamer I am creating. While I'm quite certain the only videos I'll be using it for are 16:9, I'd like for it to be versatile enough to handle other aspect ratios. So for those other ratios, how do I center the video that's shown in the StageVideo object? I just want it to be letterboxed - no scaling, zooming, or cropping.

Changing the viewPort stretches the video to fit it, which is not what I want. And the videoHeight & videoWidth properties are read-only, so it's not like I can just change those to force the video to sit back. I read on the documentation that the video aligns to the stage's top-left, maybe I can change this?

Can I center videos in StageVideo? Is this not possible, and if so, must I use a regular Video object?

Thanks for any help you can give me

mouseclick sometimes fails to work

i used an eventlistener for MouseEvent.CLICK. If I click once, it sometimes wont shoot, but when I click again it shoots. Is this a problem within flash or my mouse? It's strange. Heres the code for my fire event.

function fire(m: Event)
    {
        //reset the cooldown
        //spawn a bullet
        //set the position and the rotation of the bullet
            b.rotation = turret.rotation;
            b.x = turret.x;
            b.y = turret.y;
            //add the bullet to the parent object
            parent.addChild(b);
    }

As3 Flash video control with swipe gestures

This is for a flash app running on a windows touch based system. When swf is loaded video should play normally when user touches the screen video stops, if user drags finger right video plays forward. If user drags finger left video plays backwards.

Here is my code-

import fl.motion.MotionEvent;
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.geom.Rectangle;

var tapped = "false";
var _mouseClicked:Boolean = false;


Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onTouchBegin);
stage.addEventListener(MouseEvent.MOUSE_UP, onTouchEnd);
stage.addEventListener(MouseEvent.CLICK, onTouchClick);

function onTouchClick(evt:Event)
{
    timer.stop();
    if (tapped == "false")
    {
        tapped = "true";
        ns.pause();
        trace("movie stopped");
    }
    else
    {
        tapped = "false";
        ns.resume();
        trace("movie played");
    }
}



var curX:int = 0;
var prevX:int = 0;



function onTouchBegin(evt:Event)
{
    _mouseClicked = true;
    ns.pause();
}



function onTouchEnd(evt:Event)
{
    _mouseClicked = false;
}



function enterFrameHandler(event:Event):void
{
    if (_mouseClicked)
    {
        prevX = curX;
        curX = stage.mouseX;
        if (curX < prevX)
        {
            ns.seek(ns.time -1);

        }
        if (curX > prevX)
        {
            ns.seek(ns.time +1);
        }
    }
    else
    {
        //trace(curX);
    }
}

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

var ns:NetStream = new NetStream(nc);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.play("myVideo.flv");
function asyncErrorHandler(event:AsyncErrorEvent):void
{
    // ignore error 
}

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

I am facing 2 problems here. 1. Its forwarding jumpy like 1 second but I want it very smooth like panoramic style 2. Its really really frustrating that the backward is not working for high quality HD videos.

Someone please help. Thanks

Can't change text of movieclip in class from script in flash file

I have a class with a movieclip, in movie clip have a dynamic text named txt: When I change text for txt I see "error Cannot access a property or method of a null object reference."

package  {
    import flash.text.TextFormat;
    import flash.text.TextField;
    import flash.text.TextLineMetrics;
    import flash.display.MovieClip;
    import flash.ui.Keyboard;
    import flash.events.MouseEvent;

    public class iKeyboard {
        public var akey:MovieClip; 
        public function iKeyboard() {   
            akey = new key();
        }
        public function SetText(s:String)
        {
            txt.text = s;
        }       
    }

In script in flash file:

var ak:iKeyboard;
function Fuc1()
{
    ak:iKeyboard = new iKeyboard();
    ak.txt.text = "A"// => OK
    ak.SetText("B")// => fail error: Cannot access a property or method of a null object reference.
}

function Fuc2()
{
    ak.txt.text = "A"// fail error: Cannot access a property or method of a null object reference.
    ak.SetText("B")// => fail error: Cannot access a property or method of a null object reference.
}

Please help me resolve that !

AS3 - how to extend this function

This is first class with "gordz()" function

public class Model extends Object implements IModel
   {

     public static function gordz() : void
      {
          newobject = gallas.pop();
      }

}

Now i try to override the function but i still want that old code is executed... How can i extend this function correctly?

 public class LOL extends Model
   {
       override public static function gordz() : void
       {
         ... //New code + execute old code
       }  

   }

How to make an object randomly spawn inside of the stage only

My stage size is 640 x 1136

I want to spawn my objects randomly but only inside of the stage.

I used this

object.x = Math.random() * stage.stageHeight;

How can I make the x position spawn within the stage area?

change button color action script 3

btnPlanet.mouseEnabled = false;
btnPlanet.mouseChildren = false;

i have button and it's called btnPlanet, i want to change button color when they are disabled, but the button contain text, that if i change button color using colorTransform, it make my text dismissed, and filled with color that i use from colorTransform, can i change only color of shape in button without change text color? or make it grayscale at least? thank you, i'm sorry if i have bad grammar english

Go to specific frame after external swf has been loaded AS3

I have been looking for solutions around here but I can't seem to get it right. Basically I am trying to load an external swf after clicking on a 'Next' button and it will automatically go to a specific frame eg. frame 8 instead of frame 1.

At first I've got an error of using of using MovieClip function in a Loader and such. Here's my code

nextBtn.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF_1);

var fl_Loader1:Loader;
var fl_ToLoad1:Boolean = true;

function fl_ClickToLoadUnloadSWF_1(event:MouseEvent):void
{
if(fl_ToLoad1)
{
    fl_Loader1 = new Loader();
    fl_Loader1.load(new URLRequest("projectnowd.swf"));
    addChild(fl_Loader1);
    var fl_Loader1:MovieClip = event.target.content as MovieClip;
    fl_Loader1.gotoAndStop(8);

}
else
{
    fl_Loader1.unload();
    removeChild(fl_Loader1);
    fl_Loader1 = null;
    }
    fl_ToLoad1 = !fl_ToLoad1;
}

vendredi 29 mai 2015

AS3 Flash - How to remove dynamically created MovieClip from different function?

Using an array, I've created a MovieClip made up of tiles. I need to create the grid dynamically as there are multiple size options. If the user selects a different grid size, I need to remove the grid currently in place before adding the new grid - that is where I'm having trouble. Here is the code for creating the grid:

    public function createGrid() {

    var gridItems = new Array();
    var grid:MovieClip = new MovieClip();
    addChildAt(grid, 0);

    for (var i:int = 0; i < gridSize; i++) {
    gridItems[i] = new tile();
    gridItems[i].x = (i % gridBreak) * (gridItems[i].width );
    gridItems[i].y = int(i / gridBreak) * (gridItems[i].height);
    grid.addChild(gridItems[i]);
        }

    grid.x = stage.stageWidth/ 2 - grid.width/2;
    grid.y = (stage.stageHeight - 100) / 2 - grid.height/2;

    }

How can I remove grid from within a different function? It seems that whenever I leave the createGrid() function the reference to grid is lost.

Thanks for any suggestions!

AS3 Game spawn mechanics

I am currently working on a game with a friend, and i need some help with some code... In my game i want to make balls appear on the screen, but in a specific order, so i have created lists which will decide where to spawn the balls, and what color. Example:

var a:Array = [["green", "red", "blue", "purple"],
               ["orange", "red", "yellow", "black"],
               ["green", "green", "blue", "pink"]]

The inter dimensional arrays is because of the order i want them to spawn in(starting from the bottom). I have figured out how to spawn all the balls but when they do spawn they spawn on top of each other. Can someone please help me with this? Thanks! (i am making it in flash btw)

i got an error when i'm trying to use event that allow me to do something after my flvplayback end

here is the code

import fl.video.*;
import flash.events.Event;
import fl.video.VideoEvent;
stop();
introVideo.source = "video/Intro.flv";
introVideo.play();

introVideo.addEventListener(Event.COMPLETE, selesaiIntro);
function selesaiIntro(event:Event):void{
    gotoAndPlay(1,"Scene Gambaran Umum");
}

and i got error TypeError: Error #1009: Cannot access a property or method of a null object reference. at UIrev80_rombak_uibaru_fla::MainTimeline/frame2()[UIrev80_rombak_uibaru_fla.MainTimeline::frame2:13] at flash.display::MovieClip/gotoAndPlay() at UIrev80_rombak_uibaru_fla::MainTimeline/selesaiIntro()[UIrev80_rombak_uibaru_fla.MainTimeline::frame1:13] at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at fl.video::FLVPlayback/http://ift.tt/LifpZB at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at fl.video::VideoPlayer at fl.video::VideoPlayer i have search in many forums but i can't find the right answer i have tried use VideoEvent and i'm trying to use any other option, but it's same that it can't solved my problem, i'm sorry for poor my english grammar can someone help me? thank you very much

AS3 - Save text fields input to xml file then load them

I am trying to create a script that would save two dynamic text input fields data (entered by different users each time) (consisting from letters and numbers) into an xml file. Then I want to load some data fields from that xml back to stage. I am new to as3 so any help would be highly appreciated!

as3; stop bg sound after replay game; avoid overlapping sound

I've made a little quiz for a school project. I stuck with some sound issues. I want to play a background sound when the player hit the start btn on the start screen. After the game is finished, you can replay it. So when you come to the start screen the sound is still playing und when you hit the start btn again, the sounds are overlapping. So the best would be, after clicking the replay btn the sound stops. And when you click the start btn the sound start again. This is my code from the start screen so far:

stop();

var bgSound:Sound = new bgsnd();
var bgChannel:SoundChannel = new SoundChannel();


start_btn.addEventListener(MouseEvent.CLICK, start_quiz)


function start_quiz(event:MouseEvent):void{
    nextFrame();
    bgChannel = bgSound.play();
}

function rebtnf(event:MouseEvent):void{
    gotoAndStop(1);
    bgChannel.stop();
}

The replay btn start the function rebtnf. Works well to get to frame 1, but the sound continues to play.

Can someone help me? Hope so!

One Love, Monkeycel

iOS 8 - Starling context loss on open camera roll gallery

I am creating an app on iOS in Flash Builder, with as3. The app uses the Starling plugin: http://ift.tt/1JYM8h6

My app allows users to take photos and customise them. When attempting to access the camera or camera roll on iOS 8, I get the error message "The application lost the device context!".

On Android, I can get around this problem with this line:

            Starling.handleLostContext = true;

But I am told that iOS should never lose context (and I haven't seen it lose context on iOS 7 or below).

If I include that line in iOS 8, the application crashes at around the same point, but in this case the app crashes completely, and returns me to the home screen rather than displaying the previous message.

I have heard there are restrictions on iOS 8 with regards to the use of 64 bit/32 bit plugins and extensions, but I am not using any ANEs in this particular app. Are there any other areas where 32-bit could be causing problems or is that strictly related to ANEs?

I don't get this error on iOS 7 or below or Android, unless I set handleLostContext to false.

Any help would be appreciated.

setInterval very slow in standalone flash player

setInterval function in Flash works fine with builtin flash player (testing phase) but when I use same (published) swf on standalone player it is almost 10 times slower than that. To confirm i created a simple counter without any graphics and noticed this issue.

PS: I have checked on various player versions and even on internet browsers and even on VMWare on windows 7. I tried all other options like cpu and gpu acceleration but no improvement.

My testbench:only one frame and one dynamic text field with name "te". following is the action script

var lo=0;
function f():void{
    te.text=lo++;
}
setInterval(f,0);

Merge two images and retain its transparency

It was a while since I programmed AS3. Now I have a problem where I need to merge the two images where the upper image is a png that must retain its transparency. The upper image is an area that must pass through the lower image. A bit like a masked layer.

The result of this merge should result in a a display object. This object will later be sent to a method with the following signature:

public function addImage (
    display_object:DisplayObject,
    x:Number = 0,
    y:Number = 0,
    width:Number = 0,
    height:Number = 0,
    image_format:String = "PNG",
    quality:Number = 100,
    alpha:Number = 1,
    resizeMode:String = "None",
    blendMode:String = "Normal",
    keep_transformation:Boolean = true,
    link:String = ''
):void

Any advice is of the utmost interest. Thanks!

UPDATE;

After some struggling I've come up with this:

var bitmapDataBuffer:BitmapData = new BitmapData ( front.loader.width, front.loader.height, true );     
bitmapDataBuffer.draw ( front.loader );

var bitmapOverlay:BitmapData = new BitmapData ( front.loader.width, front.loader.height, true );
bitmapOverlay.draw ( frontBanner.loader );

var rect:Rectangle = new Rectangle(0, 0, front.loader.width, front.loader.height);
var pt:Point = new Point(0, 0);
var mult:uint = 0x00;
bitmapOverlay.merge(bitmapDataBuffer, rect, pt, mult, mult, mult, mult);

var bmp:Bitmap = new Bitmap(bitmapOverlay);

pdf.addImage(bmp,0,0,0,0,ImageFormat.PNG,100,1,ResizeMode.FIT_TO_PAGE); 

The problem is that my background image (represented by bitmapDataBuffer) will be totally overwritten by my upper image (the one I call overlay).

The overlay image is a png image. This image has a part of it that is transparent. Through this transparency I want to see my background image.

Any more suggestions?

Adding random IsoSpirite to the IsoSence

I am trying to add deffrent type of objects to a scene using as3Isolib.

I have all of my objects ( each object has different class ) in an array and then pass them using for loop to a temp spirit then add them to the sence:

for(var I=0; I<ObjectArray.length; I++)
{   
    var tempSprit:IsoSprite = new IsoSprite();
    var tempMC:* =  ObjectArray[I];

    tempSprit.sprites = [ tempMC ];
    scene.addChild(tempSprit);
}           

But nothing has been added to the scene after the issuing the render() function!

Can someone help me?

Embed swf with TLF text in a Flash Builder 4.6 Project

i'm trying to embed an swf file into a flash builder 4.6 project like this

[Embed(source="path/to/my.swf", symbol="my_symbol")]
public var MySymbolClass:Class;

Then i'm adding the symbol like this

var skin:Sprite = new MySymbolClass:Class() as Sprite;
addChild(skin);

The problem is it is not showing the texts in the embeded swf. I opened the source .fla and all the texts are TLF. If I change the text to classic text it works but I don't want to change all the texts as there are may of them.

I'm exporting the swf from flash cs6. I have already tried setting the default linkage as "Merged into code" and "runtime shared library (RSL)" at the ActionScript 3.0 settings but it does not work. If I chose "Preloaded SWF" it will cause an embed error in flash builder.

I'm using apache flex 4.12.1 SDK

Is there any solution to this?

Thanks.

Get textinput number of character in Flex

I have textinput in flex we application.

<s:TextInput id="txtGuestCount" maxChars="2" editable="false"/>

Where i limit maxChars to 2. It works when i remove editable="false" from textinput and type using keyboard.

Problem:
But same thing is not works when i do using button click like:

<s:Button width="50" height="50"  chromeColor="#ffffff" label="1" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="2" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="3" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="4" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="5" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="6" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="7" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="8" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="9" buttonMode="true" click="onNumberClick(event)"/>
<s:Button width="50" height="50"  chromeColor="#ffffff" label="0" buttonMode="true" click="onNumberClick(event)"/>

On click of button insertlabel value in textinput like:

protected function onNumberClick(event:MouseEvent):void
{
   txtGuestCount.text += event.currentTarget.label;
}

The above thing is not working. It will insert more than 2 character in textInput.

Any one help me to figure-out this issue?
How can i restrict max 2 character in textinput?

jeudi 28 mai 2015

Dealing with intances of MovieClips in AS3

I have been having trouble in getting data of MovieClips of the same names, yet stored inside different MovieClips all together.

What I Have:

  1. An Object with instance workScreen of class FashionFrenzy which contains all the rest of the MovieClips that I mention next.

Added using AS3 using addChild method in constructor code and function codes of workScreen:

  1. 12 Objects of class Shop which have a member displayArt of MovieClip type. These MovieClips are stored using an array shopMCs when then objects are created within a loop.

shopMCs array:

shopMCs = new Array(Snacks_mc,Jewellery_mc,Music_mc,Tops_mc,Bottoms_mc,Movies_mc,Purses_mc,Shoes_mc,Groceries_mc,Electronics_mc,Furniture_mc,Watches_mc,Counter_mc);

All these MovieClips are present physically over workScreen. These link perfectly and do all the functions as required.

  1. This is where my problem comes. I made a new Object of instance realShop of Class RealShop. This real shop again contains all the MCs in the shopMC array with exactly same instance name so that I have better control.

Whenever the gameTimer ; object of of Timer Class in my game which controls all the time related things in my game; reaches a specified number, the function openDayEndScreen launches.

openDayEndScreen function:

public

function openDayEndScreen(event: DayEndEvent) {

  // I am perfectly sure this event is being dispatched and this function is running.
  Time_mc.gameTimer.removeEventListener(TimerEvent.TIMER, GenerateBuyers);
  Time_mc.gameTimer.reset();


  for each(var buyer_mc: Buyer in buyers) {
    removeChild(buyer_mc);


  }

  buyers.splice(0, buyers.length); // till here I have no troubles.

  realShop.x = 0;
  realShop.y = 0;
  addChild(realShop); // I have placed realShop.
  shopMCs = new Array(Snacks_mc, Jewellery_mc, Music_mc, Tops_mc, Bottoms_mc, Movies_mc, Purses_mc, Shoes_mc, Groceries_mc, Electronics_mc, Furniture_mc, Watches_mc, Counter_mc); // this is the array

  //shops is the array containing all the Shop objects. 
  for (var bigLooper: int = 0; bigLooper < shops.length; bigLooper++) {
    //bigLooper goes to each shop one by one.
    for (var looper: int = 0; looper < shopMCs.length; looper++) {
      //looper checks for the place in shopMc where the MovieClip instance is same as the displayArt.
      if (shopMCs[looper] == shops[bigLooper].displayArt) {
        break;
        //looper is saved.
      }
    }

    if (shops[bigLooper].shopOpen) {
      upgrade_btn = new UpgradeButton; //NOT throwing errors.
      trace(realShop.shopMCs[looper]); // I am trying to access the SAME MOVIECLIP instance in the     realShop; all these are throwing errors.
      upgrade_btn.x = realShop.shopMCs[looper].x; //all these are throwing errors.
      upgrade_btn.y = realShop.shopMCs[looper].y; //all these are throwing errors.
      addChild(upgrade_btn); //NOT throwing errors.

    } else { //do nothing for a while

    }
  }



}

What this function is trying to do is place an Object of class UpgradeButton over respective MCs in the realShop , taking reference from the Shop class item's displayArt's postion; looper. I have marked down details in comments.

So, the compiler throws error when realShop.shopMCs[looper] is accessed.

Error:

TypeError: Error #1010: A term is undefined and has no properties. at FashionFrenzy/openDayEndScreen() at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at FashionFrenzy/checkDayTimerEnd() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()

How do I acchieve what I want without compiler throwing errors?

How to call function which packed with requireJS from Flash?

Suppose I have a file called flashCalls.js

require(["jquery"], function($){
    function js_getName(){
        //some code
    }
});

The function wrapped with requireJS. How can I call this function?

Error when catching objects and lives count wont decrease?

I'm currently making a catching game. So the user have to catch the right letter to get a score and go to the next question. The letters are movieclips and I made the falling animation with motion tween. I converted the avatar to a movieclip too. When the avatar hits the right letter, the user will get 100 points and when the avatar hits the wrong letter, there will be a pop up button that says "try again" and it will lost its lives by 1. Here's my code:

stop();
import flash.events.KeyboardEvent;
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveavatar);
avatarmove.addEventListener(Event.ENTER_FRAME, handleCollision);

trybutton.visible = false;
var myscore = 0; 
var mylives = 5;
score.text = myscore+"";
lives.text = mylives+"";

//Move avatar function
function moveavatar (event:KeyboardEvent):void
{
  avatarmove.x = Math.max(0,Math.min(stage.stageWidth-avatarmove.width,avatarmove.x - int(event.keyCode==37) * 10 + int(event.keyCode==39) * 10));
}

//Collision between the avatar and the letters
function handleCollision(e:Event):void
{
    if(avatarmove.hitTestObject(a_alphabet))
       {
    myscore+=100;
    a_alphabet.visible = false;
    gotoAndStop(2);
       }
  else if(avatarmove.hitTestObject(o_alphabet))
       {
    mylives-=1;
    o_alphabet.visible = false;
    trybutton.visible = true;
       }
}

//try again button
trybutton.addEventListener (MouseEvent.CLICK, ayo1);
function ayo1(event:MouseEvent):void{
  o_alphabet.visible = true;
  trybutton.visible = false;
}

I keep getting this error when the avatar hits the letter:

TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at gamecompletethewords_fla::MainTimeline/handleCollision()

And this error on the next frame:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at gamecompletethewords_fla::MainTimeline/handleCollision2()

And the the lives won't decrease when the avatar hits the wrong letter, but when I move to the next frame it will decrease by -27. It's just really weird. Can someone help me with these problems? I'm totally new to this and I have no idea how to fix it :(

Select pairs from an array (matching game) And add sound to that selection AS3 Flash CS4

I'm using a tutorial I found on Google - which works well. However, I have a few issues to make it work how I would like. This code uses a movieclip for the card faces with the back of the card on frame1 and 2-17 different pictures or movieclips.

The questions are - Is there a way to get the AScript to choose from the whole array? But still produce pairs to choose from. As it stands now - If I select the game to be 4 across by 2 down (8 cards in total) It has the back of card (frame1) and will then randomly select, but only from frames 2-5 . If I modify these lines...

public function MatchingGameObject10():void {
        // make a list of card numbers
        var cardlist:Array = new Array();
        for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
            cardlist.push(i);
            cardlist.push(i);
        }

to

public function MatchingGameObject10():void {
        // make a list of card numbers
        var cardlist:Array = new Array(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16,17,17);

I get random cards - but no pairs...

If I can ask another question here - it is - how to add a seperate sound to each card..So if it shows a Bee - the Bee.mp3 is played.. Here's the whole code..

package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.media.Sound;
import flash.media.SoundChannel;

public class MatchingGameObject10 extends MovieClip {
    // game constants
    private static const boardWidth:uint = 4;
    private static const boardHeight:uint = 2;
    private static const cardHorizontalSpacing:Number = 500;
    private static const cardVerticalSpacing:Number = 700;
    private static const boardOffsetX:Number = 50;
    private static const boardOffsetY:Number = 70;
    private static const pointsForMatch:int = 10;
    private static const pointsForMiss:int = -1;

    // variables
    private var firstCard:Card10;
    private var secondCard:Card10;
    private var cardsLeft:uint;
    private var gameScore:int;
    private var gameStartTime:uint;
    private var gameTime:uint;

    // text fields
    private var gameScoreField:TextField;
    private var gameTimeField:TextField;

    // timer to return cards to face-down
    private var flipBackTimer:Timer;

    // set up sounds
    var theFirstCardSound:FirstCardSound = new FirstCardSound();
    var theMissSound:MissSound = new MissSound();
    var theMatchSound:MatchSound = new MatchSound();

    // initialization function
    public function MatchingGameObject10():void {
        // make a list of card numbers
        var cardlist:Array = new Array();
        for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
            cardlist.push(i);
            cardlist.push(i);
        }

        // create all the cards, position them, and assign a randomcard face to each
        cardsLeft = 0;
        for (var x:uint=0; x<boardWidth; x++) {// horizontal
            for (var y:uint=0; y<boardHeight; y++) {// vertical
                var c:Card10 = new Card10();// copy the movie clip
                c.stop();// stop on first frame
                c.x = x*cardHorizontalSpacing+boardOffsetX;// set position
                c.y = y*cardVerticalSpacing+boardOffsetY;
                var r:uint = Math.floor(Math.random()*cardlist.length);// get a random face
                c.cardface = cardlist[r];// assign face to card
                cardlist.splice(r,1);// remove face from list
                c.addEventListener(MouseEvent.CLICK,clickCard);// have it listen for clicks
                c.buttonMode = true;
                addChild(c);// show the card
                cardsLeft++;
            }
        }

        // set up the score
        gameScoreField = new TextField();
        addChild(gameScoreField);
        gameScore = 0;
        showGameScore();

        // set up the clock
        gameTimeField = new TextField();
        gameTimeField.x = 450;
        addChild(gameTimeField);
        gameStartTime = getTimer();
        gameTime = 0;
        addEventListener(Event.ENTER_FRAME,showTime);
    }

    // player clicked on a card
    public function clickCard(event:MouseEvent) {
        var thisCard:Card10 = (event.target as Card10); // what card?

        if (firstCard == null) { // first card in a pair
            firstCard = thisCard; // note it
            thisCard.startFlip(thisCard.cardface+2);
            playSound(theFirstCardSound);

        } else if (firstCard == thisCard) { // clicked first card again
            firstCard.startFlip(1);
            firstCard = null;
            playSound(theMissSound);

        } else if (secondCard == null) { // second card in a pair
            secondCard = thisCard; // note it
            thisCard.startFlip(thisCard.cardface+2);

            // compare two cards
            if (firstCard.cardface == secondCard.cardface) {
                // remove a match
                removeChild(firstCard);
                removeChild(secondCard);
                // reset selection
                firstCard = null;
                secondCard = null;
                // add points
                gameScore += pointsForMatch;
                showGameScore();
                playSound(theMatchSound);
                // check for game over
                cardsLeft -= 2; // 2 less cards
                if (cardsLeft == 0) {
                    MovieClip(root).gameScore = gameScore;
                    MovieClip(root).gameTime = clockTime(gameTime);
                    MovieClip(root).gotoAndStop("gameover");
                }
            } else {
                gameScore += pointsForMiss;
                showGameScore();
                playSound(theMissSound);
                flipBackTimer = new Timer(2000,1);
                flipBackTimer.addEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
                flipBackTimer.start();
            }

        } else { // starting to pick another pair
            returnCards(null);
            playSound(theFirstCardSound);
            // select first card in next pair
            firstCard = thisCard;
            firstCard.startFlip(thisCard.cardface+2);
        }
    }

    // return cards to face-down
    public function returnCards(event:TimerEvent) {
        firstCard.startFlip(1);
        secondCard.startFlip(1);
        firstCard = null;
        secondCard = null;
        flipBackTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
    }

    public function showGameScore() {
        gameScoreField.text = "Score: "+String(gameScore);
    }

    public function showTime(event:Event) {
        gameTime = getTimer()-gameStartTime;
        gameTimeField.text = "Time: "+clockTime(gameTime);
    }

    public function clockTime(ms:int) {
        var seconds:int = Math.floor(ms/1000);
        var minutes:int = Math.floor(seconds/60);
        seconds -= minutes*60;
        var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
        return timeString;
    }

    public function playSound(soundObject:Object) {
        var channel:SoundChannel = soundObject.play();
    }
}
}

Flash HTML Not Working after being published to my website but works locally

Hi I have a weird issue regarding Flash Action Script 3.0. When I export my game as a HTML file and play it locally on my computer everything works perfectly. The issue only appears after I upload my files to my website (using Filezilla). The area that breaks is in my UI. In one of my scenes I have my game reading a text file that rapidly loads the text letter by letter like many RPG's do (Pokemon for example). You can only select buttons after the text is done. For some reason it won't load this text file when I navigate to the page via the internet but as I said before it works when I run it locally (opening html file from my desktop).

I haven't found any questions like this yet here so here I am.

I have a few theories regarding this issue but I have had no luck or idea testing them. 1. Browsers (Chrome, IE, etc) stop programs from reading files like this for security/compatibility issues maybe because of plugins (like how Chrome won't run Unity webplayer anymore unless you manually allow it with NPAPI plugins) 2. My web host won't or can't run and/or doesn't allow file reading like this. 3. The way filezilla transfers files to my web host doesn't allow or changes the way my swf works.

I have not had any issues like this before using flash (HTML or otherwise). Is there anyway to fix this or at least try to fix this?

Flex 3.5 app that doesn't work well when in Chrome?

I have a big application that is build using flex 3.5. It runs on a server environment (Apache-MySQL-PHP) and does heavy calls tot the backed using HTTPService to POST to php commands and fetch xml files. On the backend there is also a network application built with C++ that runs on localhost:55557. Flex connects to the socket and retrieves signals coming from the hardware...

For now everything is in localhost so no cross-domain issues there.

The application works perfectly fine in all browsers (Safari, Opera, Firefox) but doesn't work properly in Chrome. It loads correctly but when you click the "Start" it doesn't work and freezes, in the point when is asking to communicate with the socket. It did communicate before with the socket when the application loaded but it doesn't do it again.

Does anyone know why a flex application would have network connection issues in Chrome but not in any other browser? Does it have to do with browser security? Anyone had a same or similar issue?

want a certain path for saving and loading mp3 (air for android)

Im using shine mp3 encoder for saving mp3 file. It has a savefile method that can save a mp3 file and when that method runs (with only one argument name:String) ,automaticly some thing pop ups and ask direction for saving that mp3 file.

How can i prevent this pop up that is from air which embeded in apk.

I need a path for saving that sound and i want to play that sound later. Help me for a code that prevent the giving path from user and is fixed for later accesibility.

Thanks

AS3 - Add scroll bar to dynamically generated text field?

I'm new to actionscript 3, so please forgive me.

I am loading a text file into my flash file and then dynamically creating a text field which will take in the myBody text from that file. The problem is that the text in myBody could be very long, so I would like to add a scroll bar when needed to the dynamically generated text field. Is there any way to this?

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

var myTextField_txt:TextField = new TextField();
myTextField_txt.multiline = true;
myTextField_txt.wordWrap = true;
myTextField_txt.border = true;
myTextField_txt.height = 100;

myTextLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void {
     myTextField_txt.text = e.target.data.myBody;

     addChild(myTextField_txt);

}

myTextLoader.load(new URLRequest("mySampleFile.txt"));

Issues with FDT creating projects, had wrong JVM version before

I've been trying to use FDT for ActionScript 3 programming on Mac. I was having an issue with FDT not recognizing having installed JVM 1.8. However by adding -vm and the path to my Java install, I was able to open it.

When I open it, it opens the setup wizard, and I receive an internal error alert. However, the setup proceeds fine after that. File > New, however, says <No Applicable Items>. Using Command + New allows me to create a project, however I cannot open or access it.

I have tried reinstalling FDT, however I still have the same problem.

Children position -index- without loosing functions

I have this action script which works, I can't work out how to move startText on top position any try end up with error (#2025) or the mouse events doesn't works. Thank you.. you can see the project on http://ift.tt/1J8goFw

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

stop();


var container:Sprite = new Sprite();
addChild(container);


var startText = new StartText();
startText.x = 317.10;
startText.y = 367.75;
//container.addChild(startText);
container.addChildAt(startText,0);
//trace(container.getChildAt(0) == startText); // true
//setChildIndex(startText, numChildren -1);


//stage.setChildIndex(startText, 0);
startText.addEventListener(MouseEvent.MOUSE_OVER,removeText);
function removeText(event:MouseEvent): void {
    container.removeChild(startText);

    trace('removed');
}
var wife = new Wife();;

wife.x = 419.45;
wife.y = 916.10;
container.addChild(wife);
container.addChildAt(wife,1);
var pater;
pater.useHandCursor = true; // <---- doesn't work?
pater.mouseChildren=false;
pater.buttonMode = true;
container.addChild(pater);



pater.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
    trace('click');
    pater.play();
    this.pater.box1.play();
    this.pater.box2.play();
    this.pater.box3.play();
    this.pater.box4.play();
    this.pater.box5.play();
    this.pater.box6.play();
    this.pater.box7.play();
    this.pater.box8.play();

}

var middle;


var bl;
bl.useHandCursor = true; // <---- doesn't work?
bl.buttonMode = true;
addChild(bl);
bl.addEventListener(MouseEvent.CLICK, _openbl);
function _openbl(e:MouseEvent):void
{
    trace('open or shut');
    bl.play();


}
var br;
br.useHandCursor = true; // <---- doesn't work?
br.buttonMode = true;
addChild(br);
br.addEventListener(MouseEvent.CLICK, _openbr);
function _openbr(e:MouseEvent):void
{
    trace('open or shut');
    br.play();


}

middle.useHandCursor = true; // <---- doesn't work?
middle.buttonMode = true;
addChild(middle);
middle.addEventListener(MouseEvent.CLICK, _open);
function _open(e:MouseEvent):void
{
    trace('open the cupboard');
    middle.play();


}


var tl;
tl.useHandCursor = true; // <---- doesn't work?
tl.buttonMode = true;
addChild(tl);
tl.addEventListener(MouseEvent.CLICK, _opentl);
function _opentl(e:MouseEvent):void
{
    trace('open or shut');
    tl.play();


}
var tr;
tr.useHandCursor = true; // <---- doesn't work?
tr.buttonMode = true;
addChild(tr);
tr.addEventListener(MouseEvent.CLICK, _opentr);
function _opentr(e:MouseEvent):void
{
    trace('open or shut');
    tr.play();


}

Adobe air application quits when i try to print after a function called "show bill"?

i trying to create an air application using flash profession cc. I have functions called show bill and print bill in it. When i print directly with out showing the bill adobe air application works correctly. But when i try to use the show bill function and then try to print the bill "Adobe Air Application Quits" . Here is the code of show bill function

public function ShowBill(e: MouseEvent): void {
        total();
        Merge();
        bswap();
        billing.x = 450;
        billing.y = 100;
        billing.height = 300 ;
        billing.width = 500 ;
        addChild(billing);
        billing.close_btn1.addEventListener(MouseEvent.CLICK, rmvBilling);
        billing.close_btn1.visible = true;
        if(billing._item.item1.text != "")
        {
            billing._item.visible = true;
            billing._item.close_btn1.visible = true;
        }
        if(item2.item1.text != "")
        {
        item2.close_btn1.visible = true;
        }
        if(item3.item1.text != "")
        {
        item3.close_btn1.visible = true;
        }
        if(item4.item1.text != "")
        {
        item4.close_btn1.visible = true;
        }
        if(item5.item1.text != "")
        {
        item5.close_btn1.visible = true;
        }
        if(item6.item1.text != "")
        {
        item6.close_btn1.visible = true;
        }
        if(item7.item1.text != "")
        {
        item7.close_btn1.visible = true;
        }
        if(item8.item1.text != "")
        {
        item8.close_btn1.visible = true;
        }
        if(item9.item1.text != "")
        {
        item9.close_btn1.visible = true;
        }
        if(item10.item1.text != "")
        {
        item10.close_btn1.visible = true;
        }

        total();
    }

Here is the code for print bill

public function printContent(e: MouseEvent) {
        update1();
        billing.close_btn1.visible = false;
        billing._item.close_btn1.visible = false;
        item2.close_btn1.visible = false;
        item3.close_btn1.visible = false;
        item4.close_btn1.visible = false;
        item5.close_btn1.visible = false;
        item6.close_btn1.visible = false;
        item7.close_btn1.visible = false;
        item8.close_btn1.visible = false;
        item9.close_btn1.visible = false;
        item10.close_btn1.visible = false;

        var printJob: PrintJob = new PrintJob();
        if (printJob.start()) {
                if (billing.width < printJob.pageWidth) {
                    billing.width = printJob.pageWidth;
                    billing.scaleY = billing.scaleX;
                }
                printJob.addPage(billing);
                printJob.send();
                clear();
            }

    }
    public function update1():void{
        var phpVars:URLVariables = new URLVariables();
        var phpFileRequest:URLRequest = new URLRequest("http://localhost/icyspicy/update.php");
        phpFileRequest.method = URLRequestMethod.POST;
        phpFileRequest.data = phpVars;
        var phpLoader:URLLoader = new URLLoader();
        phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
        phpVars.systemCall="update";
        phpVars.table = String(tabNbill1.getDubTblNo.text);
        phpVars.date = String(billing.the_date.text);
        phpVars.items = String(billing._item.item1.text+","+item2.item1.text+","+item3.item1.text+","+item4.item1.text+","+item5.item1.text+","+item6.item1.text+","+item7.item1.text+","+item8.item1.text+","+item9.item1.text+","+item10.item1.text );
        phpVars.quantity = String(billing._item.q2.text+","+item2.q2.text+","+item3.q2.text+","+item4.q2.text+","+item5.q2.text+","+item6.q2.text+","+item7.q2.text+","+item8.q2.text+","+item9.q2.text+","+item10.q2.text);
        phpVars.total =String( billing.total.text);
        phpLoader.load(phpFileRequest);
        postData(mypath, getResponse);
    }

Every function is working correctly but the conflict between printbill and show bill i could not solve ..Please guys need suggestion and help..Thank You

How set wallpaper in flash as3?

Who can help me to make the photo On the desktop ..For example, to save the image in the stage in Flash and make it a background in desktop(in flash function to make an image as wallpaper)or background in phone Using the button thanks..

as an example

C/C++ DLL: Converting a const uint8_t to a String

I haven't seen C++ code in more than 10 years and now I'm in the need of developing a very small DLL to use the Ping class (System::Net::NetworkInformation) to make a ping to some remoteAddress.

The argument where I'm receiving the remoteAddress is a FREObject which then needs to be transformed into a const uint8_t *. The previous is mandatory and I can't change anything from it. The remoteAddress has to be received as a FREObject and later be transformed in a const uint8_t *.

The problem I'm having is that I have to pass a String^ to the Ping class and not a const uint8_t * and I have no clue of how to convert my const uint8_t * to a String^. Do you have any ideas?

Next is part of my code:

// argv[ARG_IP_ADDRESS_ARGUMENT holds the remoteAddress value.
uint32_t nativeCharArrayLength = 0;
const uint8_t * nativeCharArray = NULL;
FREResult status = FREGetObjectAsUTF8(argv[ARG_IP_ADDRESS_ARGUMENT], &nativeCharArrayLength, &nativeCharArray);

Basically the FREGetObjectAsUTF8 function fills the nativeCharArray array with the value of argv[ARG_IP_ADDRESS_ARGUMENT] and returns the array's length in nativeCharArrayLength. Also, the string uses UTF-8 encoding terminates with the null character.

My next problem would be to convert a String^ back to a const uint8_t *. If you can help with this as well I would really appreciate it.

As I said before, non of this is changeable and I have no idea of how to change nativeCharArray to a String^. Any advice will help.

PS: Also, the purpose of this DLL is to use it as an ANE (Air Native Extension) for my Adobe Air app.

How do you collect timer string data in object

I have a simple count-up timer that displays milliseconds, seconds, and minutes in real time. When a certain condition is met the stop timer is triggered. I am confused on how to get that time stored in an object and then displayed by shortest time first.

var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;

function timerTickHandler(Event:TimerEvent):void
{
    timerCount += 100;
    toTimeCode(timerCount);
}

function toTimeCode(milliseconds:int) : void 
{
//creating a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);

//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);

//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;

//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}

VPAID ad contentPauseRequest issue as3

All my VPAIDEvent methods are working with my JW Player but content doesn't stop when the ad started.

I checked and there is a method called pauseContentRequest but it is not in my VPAIDEvent list.

How will i call that event to stop the content of the player?

Thanks

as3 Error #2048: Security sandbox violation when trying to connect through socket

I have a SWF file embedded in a PHP web application. All local and on my system. I want to make a socket connection from my SWF to localhost:4242 (which is an eye tracker api). When I run SWF using flash player everything works fine. But when I run it from browser I get:

Security Error: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048: Security sandbox violation: http://localhost/graph/assets/swf/Graph.swf cannot load data from http://localhost:4242."]

I added crossdomain.xml to my local web server (easy php) like this:

<?xml version="1.0" ?>
  <cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*" to-ports="*" secure="false"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

and this is my action script for socket connection:

socket = new Socket();
Security.allowDomain("*");
Security.allowInsecureDomain("*");
Security.loadPolicyFile("http://localhost/crossdomain.xml");
socket.addEventListener(Event.CONNECT, onSocketConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(IOErrorEvent.IO_ERROR, onError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecError);

socket.connect("http://localhost", 4242);

I went through everything on web for solving this problem. I don't know what the problem is and what should I do.

Flash AS3 - 1046: Type was not found or was not a compile-time constant..how to add group of movie clips?

My old project is without an issue: I used a movie clip PaterMove with instance Box, Inside I have 8x the same movie clip Box3D I just change instance for each one, which is up, up2, till up8.

import flash.display.*;
import flash.events.*;
stop();

var box;

box.useHandCursor = true; // <---- doesn't work?
box.mouseChildren=false;
box.buttonMode = true;
addChild(box);

box.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
trace('click');
box.play();
this.box.up.play();
this.box.up2.play();
this.box.up3.play();
this.box.up6.play();
this.box.up5.play();
this.box.up4.play();
this.box.up8.play();
this.box.up7.play();
}

I have this simple code to by able to click on each box and make them moving. but the issue is Box3D doesn’t move how I need. I made updated project where I don’t use the same movie clip, bot I have especial one for each position. Link to see old project: http://ift.tt/1J8goFw

Now I used movie clip PN with instance name pater, and I have inside 8 different movie clips call box1 till box8. with instance name box1 till box8 I believe that made the problem, but what should I add to the code ???

import flash.display.*;
import flash.events.*;
stop();


var pater;


pater.useHandCursor = true; // <---- doesn't work?
pater.mouseChildren=false;
pater.buttonMode = true;
addChild(pater);

pater.addEventListener(MouseEvent.CLICK, _click);
function _click(e:MouseEvent):void
{
trace('click');
pater.play();
this.pater.box1.play();
this.pater.box2.play();
this.pater.box3.play();
this.pater.box4.play();
this.pater.box5.play();
this.pater.box6.play();
this.pater.box7.play();
this.pater.box8.play();


}

How to decode Base64(uncompressed) TMX data element contents?

I have been trying to decode the Base64 contents of the data element in a TMX file with AS3. I am using mx.utils.Base64Decoder to decode the contents.

Here is my 1x1 layer data without the encoding (I'm not sure if the encoded data is in XML format):

<tile gid="1"/>

Here is my layer encoded:

AQAAAA==

When I try to decode the data, the return value is empty. I tried to decode the data with an online Base64 decoder but that showed an empty value also.

mercredi 27 mai 2015

Pass variable via URLRequest

I am displaying external swf in an other swf. I read XML file that keeps external swf path. At some point I need the result of a function in the external one. So is it possible to pass the result and fetch it over URLRequest?

Here is the code:

var contentLoader:Loader;
var context:LoaderContext = new LoaderContext();        
contentLoader = new Loader();       
contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, contentLoadingCompleteActions);
contentLoader.load(new URLRequest(url), context);


url comes from XML parser as I said before. I want to load the swf and also get the selected variable if possible.


A (main swf) - imports swf via URLRequest

B (imported swf) - has to send a value to A

Audio recorded file corrupted issue in Actionscript

I recorded voice samples from my microphone using Adobe Flash Builder 4.6 / AIR, voice recorded successfully. I first converted voice data(byte array) to base64 format in actionscript then I converted that base64 data to WAV file using my PHP code. but that WAV file throw file corrupted issue in RiffPad.

RIFFPad is a viewer for RIFF formatted files like WAV, AVI.

// -- saves the current audio data as a .wav file
    protected function onSubmit( event:Event ):void {
        alertBox.show("Processing ... please wait.");

        stopPlayback();
        stopRecording();
        playBtn.enabled = recordBtn.enabled = submitBtn.enabled = false;
        var position:int = capture.buffer.position;
        var wavWriter:WAVWriter = new WAVWriter()
        var wavWriter1:WaveEncoder = new WaveEncoder()
        wavWriter.numOfChannels = 1;
        wavWriter.samplingRate = 22050;
        wavWriter.sampleBitRate = 16; 
        var wavBytes:ByteArray = new ByteArray;
        capture.buffer.position = 0;
        wavBytes = wavWriter1.encode( capture.buffer, 1, 16, 22050);
        capture.buffer.position = position;
        wavBytes.position=0;
        submitVoiceSample(Base64_new.encodeByteArray(wavBytes));
    }

WAV Data Writer function:

/**
     * 
     * @param samples
     * @param channels
     * @param bits
     * @param rate
     * @return 
     * 
     */     
    public function encode( samples:ByteArray, channels:int=1, bits:int=16, rate:int=22050 ):ByteArray
    {
        var data:ByteArray = create( samples );

        _bytes.length = 0;
        _bytes.endian = Endian.LITTLE_ENDIAN;

        _bytes.writeUTFBytes( WaveEncoder.RIFF );
        _bytes.writeInt( uint( data.length + 44 ) );
        _bytes.writeUTFBytes( WaveEncoder.WAVE );
        _bytes.writeUTFBytes( WaveEncoder.FMT );
        _bytes.writeInt( uint( 16 ) );
        _bytes.writeShort( uint( 1 ) );
        _bytes.writeShort( channels );
        _bytes.writeInt( rate );
        _bytes.writeInt( uint( rate * channels * ( bits >> 3 ) ) );
        _bytes.writeShort( uint( channels * ( bits >> 3 ) ) );
        _bytes.writeShort( bits );
        _bytes.writeUTFBytes( WaveEncoder.DATA );
        _bytes.writeInt( data.length );
        _bytes.writeBytes( data );
        _bytes.position = 0;

        return _bytes;
    }

ByteArray to Base64 encoding

public static function encode(data:ByteArray):String
    {
        var out:ByteArray = new ByteArray();
        //Presetting the length keep the memory smaller and optimize speed since there is no "grow" needed
        out.length = (2 + data.length - ((data.length + 2) % 3)) * 4 / 3; //Preset length //1.6 to 1.5 ms
        var i:int = 0;
        var r:int = data.length % 3;
        var len:int = data.length - r;
        var c:uint; //read (3) character AND write (4) characters
        var outPos:int = 0;
        while (i < len)
        {
            //Read 3 Characters (8bit * 3 = 24 bits)
            c = data[int(i++)] << 16 | data[int(i++)] << 8 | data[int(i++)];

            out[int(outPos++)] = _encodeChars[int(c >>> 18)];
            out[int(outPos++)] = _encodeChars[int(c >>> 12 & 0x3f)];
            out[int(outPos++)] = _encodeChars[int(c >>> 6 & 0x3f)];
            out[int(outPos++)] = _encodeChars[int(c & 0x3f)];
        }

        if (r == 1) //Need two "=" padding
        {
            //Read one char, write two chars, write padding
            c = data[int(i)];

            out[int(outPos++)] = _encodeChars[int(c >>> 2)];
            out[int(outPos++)] = _encodeChars[int((c & 0x03) << 4)];
            out[int(outPos++)] = 61;
            out[int(outPos++)] = 61;
        }
        else if (r == 2) //Need one "=" padding
        {
            c = data[int(i++)] << 8 | data[int(i)];

            out[int(outPos++)] = _encodeChars[int(c >>> 10)];
            out[int(outPos++)] = _encodeChars[int(c >>> 4 & 0x3f)];
            out[int(outPos++)] = _encodeChars[int((c & 0x0f) << 2)];
            out[int(outPos++)] = 61;
        }

        return out.readUTFBytes(out.length);
    }

    public static function decode(str:String):ByteArray
    {
        var c1:int;
        var c2:int;
        var c3:int;
        var c4:int;
        var i:int = 0;
        var len:int = str.length;

        var byteString:ByteArray = new ByteArray();
        byteString.writeUTFBytes(str);
        var outPos:int = 0;
        while (i < len)
        {
            //c1
            c1 = _decodeChars[int(byteString[i++])];
            if (c1 == -1)
                break;

            //c2
            c2 = _decodeChars[int(byteString[i++])];
            if (c2 == -1)
                break;

            byteString[int(outPos++)] = (c1 << 2) | ((c2 & 0x30) >> 4);

            //c3
            c3 = byteString[int(i++)];
            if (c3 == 61)
            {
                byteString.length = outPos
                return byteString;
            }

            c3 = _decodeChars[int(c3)];
            if (c3 == -1)
                break;

            byteString[int(outPos++)] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);

            //c4
            c4 = byteString[int(i++)];
            if (c4 == 61)
            {
                byteString.length = outPos
                return byteString;
            }

            c4 = _decodeChars[int(c4)];
            if (c4 == -1)
                break;

            byteString[int(outPos++)] = ((c3 & 0x03) << 6) | c4;
        }
        byteString.length = outPos
        return byteString;
    }

    public static function InitEncoreChar():Vector.<int>
    {
        var encodeChars:Vector.<int> = new Vector.<int>(64, true);

        // We could push the number directly
        // but I think it's nice to see the characters (with no overhead on encode/decode)
        var chars:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        for (var i:int = 0; i < 64; i++)
        {
            encodeChars[i] = chars.charCodeAt(i);
        }

        return encodeChars;
    }

I send that base64 data to my service request php side i got the '$this->request->voiceSample' parameter and decode base64 to .wav file

 file_put_contents('name.wav', base64_decode($this->request->voiceSample));

After load that "name.wav" file in Riffpad I got issue

The file seems to be corrupt for a RIFF.

Any one please give me the advice to solve this issue...

AS3 SoundChannel stop() not working

I have a SoundHandler class with the following variables:

private static var musicChannel: SoundChannel;
private static var effectsChannel: SoundChannel;
private static var narrationChannel: SoundChannel;
private static var narrationMuted:Boolean;

The effects and music channels work fine, but the narration channel doesn't stop when stop() is called. Here is the function:

    public static function playNarration(narrationClassName: String): void {
        if (!narrationMuted) {
            narrationChannel.stop(); //NOT WORKING--THE SOUND KEEPS PLAYING!
            var classReference: Class = getDefinitionByName(narrationClassName) as Class;
            var s: Sound = new classReference();
            narrationChannel = s.play();
        }
    }

SoundMixer.stopAll() DOES stop the narration sound, but I can't use it because it also stops the music and effects sounds.

I suspect that stop() isn't working because of how I'm creating the Sound object, but I'm not sure. Loading externally doesn't fix the problem:

     public static function playNarration(narrationClassName: String): void {
            if (!narrationMuted) {
                narrationChannel.stop();
                var s: Sound = new Sound();
                s.addEventListener(Event.COMPLETE, onNarrationSoundLoaded);
                var req: URLRequest = new URLRequest("sounds/Narration/sub_narr_1.mp3");
                s.load(req);
            }
        }
        private static function onNarrationSoundLoaded(e: Event): void {
            var localSound: Sound = e.target as Sound;
            narrationChannel = localSound.play();
        }

Any help is appreciated. Thanks!

Autocomplete search for any word in the sentence

I'm using an autocomplete for my flash app. The autocomplete uses an external text file. When I'm typing the first word of the sentence, it display all the sentences that begins with this word.

Is it possible to display all sentence that have this word (and not just the begining of the sentence) ?

Exemple : I've got two phrases : "I'm going to school" and " I'm going to look for him".

I would like to be able to type "school" and that it displays the first sentence.

Do you know how I can do that ? For now, I have to type "I'm going to s" in order to display the first sentence.

Here's my code :

urlLoader.load(new URLRequest("test.txt"));
            urlLoader.addEventListener(Event.COMPLETE, loadComplete);
            inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);

 function loadComplete(e:Event):void
        {
            suggestions = e.target.data.split(",");
        }

         function suggest(e:KeyboardEvent):void
        {
            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];

            for (var j:int = 0; j < suggestions.length; j++)
            {
                if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)
                {
                    var term:TextField = new TextField();
                    term.width = 300;
                    term.height = 20;
                    term.x = 70;
                    term.y = (20 * suggested.length) + 314;
                    term.border = true;
                    term.borderColor = 0x353535;
                    term.background = true;
                    term.backgroundColor = 0xFF9900;
                    term.textColor = 0x4C311D;
                    term.defaultTextFormat = format;

                    term.addEventListener(MouseEvent.MOUSE_UP, useWord);
                    term.addEventListener(MouseEvent.MOUSE_OVER, hover);
                    term.addEventListener(MouseEvent.MOUSE_OUT, out);
                    term.addEventListener(MouseEvent.CLICK, tellMe);

                    addChild(term);
                    textfields.push(term);

                    suggested.push(suggestions[j]);

                    term.text = suggestions[j];
                }

            }

            if (inputField.length == 0)
            {
                suggested = [];

                for (var k:int = 0; k < textfields.length; k++)
                {
                    removeChild(textfields[k]);
                }

                textfields = [];
            }

            if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
            {
                currentSelection++;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.UP && currentSelection > 0)
            {
                currentSelection--;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.ENTER)
            {
                inputField.text = textfields[currentSelection].text;

                suggested = [];

                for (var l:int = 0; l < textfields.length; l++)
                {
                    removeChild(textfields[l]);
                }

                textfields = [];
                currentSelection = 0;
            }
        }

         function useWord(e:MouseEvent):void
        {
            inputField.text = e.target.text;

            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];
        } 

Thank you

I keep getting 'ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller' inside timer event

I'm trying to remove this item from the stage and keep getting this error. The code seems to work and the object is removed but the game seems kinda buggy.

Here's the full error: "ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. at flash.display::DisplayObjectContainer/removeChild() at JumpingGame/onTick2()[E:\Folder\Folder\Folder\Folder\JumpingGame.as:95] at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()"

The error is pointing to:

  • removeChild(enemy)
  • removeChild(leg);
  • removeChild(life);

I'm also getting: "TypeError: Error #1009: Cannot access a property or method of a null object reference" on this line theLives.text = liveLives.toString();

Here's my code:

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

    public class JumpingGame extends MovieClip 
    {
        public var army:Array;
        public var powerups:Array;
        public var pluslives:Array;

        public var newDoodle:doodle;

        public var enemyTimer:Timer;
        public var legTimer:Timer;
        public var lifeTimer:Timer; 

        public function JumpingGame() 
        {

            enemyTimer = new Timer( 40 );
            enemyTimer.addEventListener( TimerEvent.TIMER, onTick );
            enemyTimer.start();

            legTimer = new Timer( 20 );
            legTimer.addEventListener( TimerEvent.TIMER, onTick2 );
            legTimer.start();

            lifeTimer = new Timer( 30 );
            lifeTimer.addEventListener( TimerEvent.TIMER, onTick3 );
            lifeTimer.start();

            army = new Array();
            var newEnemy = new Enemy( 100, -15 );
            army.push( newEnemy );
            addChild( newEnemy );

            powerups = new Array();
            var newLeg = new Leg( 300, -15 );
            powerups.push( newLeg );
            addChild( newLeg );

            pluslives = new Array();
            var newLife = new Plus1( 300, -15 );
            pluslives.push( newLife );
            addChild( newLife );

            newDoodle = new doodle();
            addChild( newDoodle );
            newDoodle.y = stage.stageHeight - 50;
            newDoodle.x = stage.stageWidth / 2;
        }

        public function onTick( timerEvent:TimerEvent ):void
        {
            if (Math.random() <0.005 )
            {
                var randomX:Number = Math.random() * 320;
                var newEnemy:Enemy = new Enemy( randomX, -15 );
                army.push( newEnemy );
                addChild( newEnemy );
            }

            for each ( var enemy:Enemy in army )
            {
                enemy.moveDownABit();
                if (newDoodle.hitTestObject( enemy ) )
                {
                    //gotoAndPlay ("Game Over");
                    removeChild(enemy);
                    liveLives -= 1;
                    theLives.text = liveLives.toString();

                }
            }
        }

        public function onTick2( timerEvent:TimerEvent ):void
        {
            if (Math.random() <0.008 )
            {
                var randomX2:Number = Math.random() * 320;
                var newLeg:Leg = new Leg( randomX2, -15 );
                powerups.push( newLeg );
                addChild( newLeg );
            }

            for each ( var leg:Leg in powerups )
            {
                leg.moveDownABit2();
                if (newDoodle.hitTestObject( leg ) )
                {
                    //gotoAndPlay ("Game Over");
                    removeChild(leg);
                    liveScore += 2000;
                    theScore.text = liveScore.toString();
                }
            }

        }

        public function onTick3( timerEvent:TimerEvent ):void
        {
            if (Math.random() <0.001 )
            {
                var randomX3:Number = Math.random() * 320;
                var newLife:Plus1 = new Plus1( randomX3, -15 );
                pluslives.push( newLife );
                addChild( newLife );
            }

            for each ( var life:Plus1 in pluslives )
            {
                life.moveDownABit3();
                if (newDoodle.hitTestObject( life ) )
                {
                    //gotoAndPlay ("Game Over");
                    removeChild(life);
                    liveLives += 1;
                    theLives.text = liveLives.toString();

                }
            }

        }
    }
}

Autocomplete on phone - AS3

I've made an autocomplete that work very well in the swf file.

enter image description here

very simple, when the user write the first letter, a suggestion is made with words.

I've published my project for IOS. When I'm trying it on the Iphone, nothing is suggested when I'm typing the first letter. I have to write the first letter and then clicked on "enter" in order to display the suggestions...

I don't want the users to "validate" in order to have the suggestion but simply by typing a letter.

Do you know what could be the problem ? Anyone can help me ?

Here is my code :

urlLoader.load(new URLRequest("test.txt"));
            urlLoader.addEventListener(Event.COMPLETE, loadComplete);
            inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);

 function loadComplete(e:Event):void
        {
            suggestions = e.target.data.split(",");
        }

         function suggest(e:KeyboardEvent):void
        {
            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];

            for (var j:int = 0; j < suggestions.length; j++)
            {
                if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)
                {
                    var term:TextField = new TextField();
                    term.width = 300;
                    term.height = 20;
                    term.x = 70;
                    term.y = (20 * suggested.length) + 314;
                    term.border = true;
                    term.borderColor = 0x353535;
                    term.background = true;
                    term.backgroundColor = 0xFF9900;
                    term.textColor = 0x4C311D;
                    term.defaultTextFormat = format;

                    term.addEventListener(MouseEvent.MOUSE_UP, useWord);
                    term.addEventListener(MouseEvent.MOUSE_OVER, hover);
                    term.addEventListener(MouseEvent.MOUSE_OUT, out);
                    term.addEventListener(MouseEvent.CLICK, tellMe);

                    addChild(term);
                    textfields.push(term);

                    suggested.push(suggestions[j]);

                    term.text = suggestions[j];
                }

            }

            if (inputField.length == 0)
            {
                suggested = [];

                for (var k:int = 0; k < textfields.length; k++)
                {
                    removeChild(textfields[k]);
                }

                textfields = [];
            }

            if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
            {
                currentSelection++;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.UP && currentSelection > 0)
            {
                currentSelection--;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.ENTER)
            {
                inputField.text = textfields[currentSelection].text;

                suggested = [];

                for (var l:int = 0; l < textfields.length; l++)
                {
                    removeChild(textfields[l]);
                }

                textfields = [];
                currentSelection = 0;
            }
        }

         function useWord(e:MouseEvent):void
        {
            inputField.text = e.target.text;

            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];
        } 

Thank you

Can I specify which icon set should be used in an AIR application descriptor?

I don't want to use the same exact icons on my Android and iOS app, is there a way to specify a different folder or filename to use? Or do I have to do a release build, swap the icons and then do another release?

read multiple lines when loading txt file in AS3

So I've got a searchBar and when I'm typing a word, the searchab suggests word from a text file. Problem : I can only have one line in my txt file. If I put a word in a second line, the search bar won't suggest it..

Do you know how can I make AS3 to load all the lines from my txt file ?

Thx

Here's my code :

import flash.display.Sprite;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.events.Event;
    import flash.ui.Keyboard;
    import flash.events.KeyboardEvent;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.text.TextFormat;


         var urlLoader:URLLoader = new URLLoader();
         var suggestions:Array = new Array();
         var suggested:Array = new Array();
         var textfields:Array = new Array();
         var format:TextFormat = new TextFormat();
         var currentSelection:int = -1;


            urlLoader.load(new URLRequest("Sports.txt"));
            urlLoader.addEventListener(Event.COMPLETE, loadComplete);
            inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);

            format.font = "Helvetica";
            format.size = 12;
            format.bold = true;

         function loadComplete(e:Event):void
        {

            suggestions = e.target.data.split(",");
        }

         function suggest(e:KeyboardEvent):void
        {
            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];

            for (var j:int = 0; j < suggestions.length; j++)
            {
                if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)
                {
                    var term:TextField = new TextField();
                    term.width = 300;
                    term.height = 20;
                    term.x = 70;
                    term.y = (20 * suggested.length) + 314;
                    term.border = true;
                    term.borderColor = 0x353535;
                    term.background = true;
                    term.backgroundColor = 0xFF9900;
                    term.textColor = 0x4C311D;
                    term.defaultTextFormat = format;

                    term.addEventListener(MouseEvent.MOUSE_UP, useWord);
                    term.addEventListener(MouseEvent.MOUSE_OVER, hover);
                    term.addEventListener(MouseEvent.MOUSE_OUT, out);
                    term.addEventListener(MouseEvent.CLICK, tellMe);

                    addChild(term);
                    textfields.push(term);

                    suggested.push(suggestions[j]);

                    term.text = suggestions[j];
                }

            }

            if (inputField.length == 0)
            {
                suggested = [];

                for (var k:int = 0; k < textfields.length; k++)
                {
                    removeChild(textfields[k]);
                }

                textfields = [];
            }

            if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
            {
                currentSelection++;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.UP && currentSelection > 0)
            {
                currentSelection--;
                textfields[currentSelection].textColor = 0x4C311D;
            }

            if(e.keyCode == Keyboard.ENTER)
            {
                inputField.text = textfields[currentSelection].text;

                suggested = [];

                for (var l:int = 0; l < textfields.length; l++)
                {
                    removeChild(textfields[l]);
                }

                textfields = [];
                currentSelection = 0;
            }
        }

         function useWord(e:MouseEvent):void
        {
            inputField.text = e.target.text;

            suggested = [];

            for (var i:int = 0; i < textfields.length; i++)
            {
                removeChild(textfields[i]);
            }

            textfields = [];
        }

Embedded PNG: 1034 Type Coercion Failed

Every single tutorial says to do it like this, which used to work:

[Embed(source="/../images/MyImage.png",mimeType="image/png",smoothing="true")]
private static var ImageClass:Class;

//[...]

var bitmap:Bitmap = new ImageClass();

Again, this used to work, but now (when I use PNGs) it gives me Error #1034: Type Coercion failed: cannot convert MyImage_png$3e9131867d9df437bb131fa0f25e1d80-479819629@c756f89 to flash.display.Bitmap.

Am I doing something wrong? How do you embed a PNG as a Bitmap?

How to escape an equals sign in param element's value attribute?

I have an embed tag that will be used to store a SWF object. I've been following this documentation here

http://ift.tt/1FbbgL8

I need to create a parameter with a name equal to FlashVars.

I need to store an API token in the value attribute. The problem is there is an equals sign in the token itself.

My token is

var token = "GABVZgTs_____2R2cHlzNHd5ZXg3Z2M0OXdoaDY3aHdrbo80onzX6aHp2ytZg17l7bE="

<object data="http://ift.tt/1LK2xoD">
  <param name=FlashVars
         value="token=GABVZgTs_____2R2cHlzNHd5ZXg3Z2M0OXdoaDY3aHdrbo80onzX6aHp2ytZg17l7bE="></param>
</object>

The result of the value attribute is to be embedded inside quotes. Then inside the quotes you have the syntax

key=value

but the value itself has an equals sign in it. Am I supposed to embed the value inside the value inside quotation marks?

Here are the API instructions

The API SWF must be embedded from http://ift.tt/1LK2xoD with the following flashvars arguments:

playbackToken: a valid playback token, retrieved from the getPlaybackToken Web Service API method

domain: the domain that the SWF will be embedded in

listener" the name of a JS object to receive callbacks

enableLogging: Optional, provides debug logging when set to 1 The easiest way to embed the SWF is to use the SWFObject library.

Status callbacks will be called on whatever object was passed in as the callback parameter. For example if foo was supplied then the ready callback will be called as window.foo.ready().

Methods can be called directly on the embed object — the or tag’s DOM node. Since Flash itself defines some methods all methods are prefixed with rdio_.

To call the play method on an API SWF with ID bar you could call:

I've also been using this source

http://ift.tt/1LK2xVD

how to embed youku video in Flash CC

how to embed youku video in Flash CC?

like this post did with youtube video.

How to load a mp3 file from internal storage?

I'm working on a mobile project which needs to play a mp3 from internal storage.

My code:

Var r:URLRequest = new URLRequest("/storage/emulated/0/mysound.mp3");

Var s:Sound = new Sound (r);
S.play();

But the path is not correct. What is the path of internal storage?

Action Script Next Button replay

I have an ActionScript music player that is pulling songs from an xml file. I have a Play button and a Next Button. I have 4 songs, but when I press the next button until the last song is playing, the next time I press next it doesn't goe back to the first song.

Here is the next button code:

//Next Song Functions
function nextSong(e:Event):void {
        if (currentIndex < (songlist.length() +1)) {//Next Song(+1)
               currentIndex++;
        } else {
               currentIndex=0;
        }
        //New Request for Next Song
        var nextSongFunc:URLRequest=new URLRequest(songlist[currentIndex].file);
        var nextTitle:Sound=new Sound(nextSongFunc);
        sc.stop();
        MusicName.text=songlist[currentIndex].name;//Writing New Song's name
        sc=nextTitle.play();
        currentSound=nextTitle;
        sc.addEventListener(Ev9ent.SOUND_COMPLETE, nextSong);
}

What should I change so when I press next and there is no next music, it goes to the first one?

AS3 alpha of multiple objects adds up

It seems that when I set alpha on a DisplayObjectContainer, then it works on each individual child separately and not on the container as a whole. Consequently I start seeing overlap regions which are normally not visible.

enter image description here

My question is - How do I fade a container as a whole?

Take every second element from array in as3

I want to take out every second element from an array to create a new array from.

Thanks, JacquesCA

mardi 26 mai 2015

How to use CitrusSprite.velocity

I have the following function in a scene that extends citrus.core.starling.StarlingState - it loads the PlayerRun animation and displays it on the screen. For the most part, this code works: I see the sprite on the screen (it's running in place).

protected final override function DrawScene ():void
{
    Player = new CitrusSprite ( "Player" );

    Player.velocity = [60, 0]; // Doesn't seem to have an effect
    Player.x = 40;
    Player.y = 40;

    var oClip:MovieClip = new MovieClip ( Resources.getTextures ( 
        "PlayerRun" ), 24 );

    Player.view = oClip;

    add ( Player );
}

I'm not sure how I'm supposed to use the velocity property - there's no documentation for it and no matter what numbers I use in the code above, it doesn't change the display: the animation plays but the sprite is stationary (it doesn't move horizontally as I would expect it).

Am I using the velocity property incorrectly? Does Citrus support sprite velocity or is this something I'd have to implement myself?