dimanche 31 janvier 2016

Object information for assets in SWF

I have an swf file which I wish include in my library (Flash professional) and use it's assets in action script. I have not created the SWF, hence have no information about naming of the assets it contains. I am able to view the assets by adding the swf to library. However I am unable to see the names/other properties of the assets. Is there any way to read information about contents of the swf

Can anyone help me change this code from AS2 to AS3

This will be a simple clock. I've been using AS2 since I learned Flash in early 2000s. It's time to move on.

for (a=1; a<60; a++) { duplicateMovieClip("dot0", "dot"+a, 10+a); _root["dot"+a]._rotation = a*6; _root["dot"+a].gotoAndStop(1); }

Problems with adding Score in text field for AS3

new here and learning flash AS3. I am having a problem with a game I'm working on. I am a teacher and it is a review game. I would like to display the score as part of a text field. At the very beginning I declare the variable:

var wrongScore:Number = 0;
var correctScore:Number = 0;

Then when an object is dragged and dropped I am trying to display an updated score. It is displaying "Number Correct:" and "Number Wrong:" but not giving the value of correctScore or wrongScore.

 function left1Drop (e:MouseEvent):void{
 if (left1.hitTestObject(leftTarget))
 {
 left1.stopDrag();
  correct.play();
  correctScore += 1;
  correctScoreText.text= "Number Correct:" + String(correctScore);

  left1.removeEventListener(MouseEvent.MOUSE_DOWN, left1Drag);
 }
    if (left1.hitTestObject(rightTarget))
  {
left1.stopDrag();
left1.x = left1StartX;
left1.y = left1StartY;
wrong.play();
wrongScore += 1;
wrongScoreText.text = "Number Wrong:" + String (wrongScore);

 }
else
{
    left1.stopDrag();
}
}

I am guessing my problem is somewhere in the code below. But I believe I am typing it exactly as I've seen it elsewhere.

  correctScoreText.text= "Number Correct:" + String(correctScore);

Thank you in advance for any help you can offer!!!

Forcing SWF to load file in local driver of server before sending over browser

I am building a flash application which requires loading of an xml file using URLLoader. While developing application in my local machine with flash professional I can easily load it by

        private var myLoader:URLLoader = new URLLoader(new URLRequest("./com/assets/config.xml"));

When I publish the application and click on the html generated and the app loads on browser perfectly.

If I make a server (localhost:1111) that delivers the html file over browser on connect, the html file doesn't load the application (.swf).

While trying to debug it, I found that if I change the myLoader variable as below, the html file loads the swf properly.

    private var myLoader:URLLoader = new URLLoader(new URLRequest("http://localhost:1111/com/assets/config.xml"));

I believe the SWF is making another GET request after the html loads on my browser, that is the reason the SWF doesn't work without the change.

Is there any way I can load the xml file in SWF before it gets delivered over browser. This is to avoid another call to the server. I appreciate any help in clarifying my understanding and suggestion for workaround.

ActionScript3 LoadVars

I am trying to find out what I need to do do respond to an ActionScript LoadVars code.

Here is the code

    function loadItemData(playerID)
   {
      this.responseVars = new LoadVars();
      this.responseVars.onLoad = com.business.util.Delegate.create(this,this.handleloadItemData);
      this.requestVars = new LoadVars();
      this.requestVars.player_id = playerID;
      this.requestVars.sendAndLoad(this.serverURL,this.responseVars,"POST");
   }
   function handleloadItemData(success)
   {
      trace("Server.handleloadItemData() -> success: " + success);
      if(Number(this.responseVars.e) == 0)
      {
         this.item = {};
         this.item.playerID = Number(this.responseVars.player_id);
         this.item.type = Number(this.responseVars.item_id);
         this.item.floorID = Number(this.responseVars.item_floor_id);
         this.item.furniture = [];
         var _loc5_ = String(this.responseVars.map).split(",");
         var _loc4_ = 0;
         while(_loc4_ < _loc5_.length)
         {
            var _loc2_ = _loc5_[_loc4_].split("|");
            if(_loc2_.length > 1)
            {
               if(!isNaN(_loc2_[0]))
               {
                  var _loc3_ = {};
                  _loc3_.id = Number(_loc2_[0]);
                  _loc3_.x = Number(_loc2_[1]);
                  _loc3_.y = Number(_loc2_[2]);
                  _loc3_.frame_1 = Number(_loc2_[3]) || 1;
                  _loc3_.frame_2 = Number(_loc2_[4]) || 1;
                  this.item.furniture.push(_loc3_);
               }
            }
            _loc4_ = _loc4_ + 1;
         }
         this.dispatchEvent({type:com.business.internal.itemviewer.Server.ITEM_DATA_LOADED,item:this.item});
      }
      else
      {
         trace("Server.handleloadItemData() -> Error");
      }
   }

So I am trying to find for handleItemData what the response would be like. For my PHP file

    <?php
$array = array(
    "player_id" => "81",
    "item_id" => "35",
    "item_floor_id" => "7",
    "furniture" => "",
);

print_r($array);
?>

But it doesn't load am I sending the correct sort of response back from my PHP file.

Thank you

C# Multi-threaded Server - Cross Domain Policy

I have a server, listening for connections from a SWF file in browser.

When running on local, it picks up a connection then drops it very soon after leaving in the log:

[31/1/2016 18:10:14] 127.0.0.1connected. Full 127.0.0.1:58482

[31/1/2016 18:10:14] Got < policy-file-request/> from client 0

[31/1/2016 18:10:16] Client0 disconnected and removed.

This is not logged when the server is ran and the client is launched in debug mode in flashdevelop, but the client connects and acts as desired.

I am including my TcpClient class, have i made a mistake or typo or should this be behaving differently when ran in browser and not in flashdevelop?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ParticleFramework.Communication
{
    class TcpClient
    {
        #region Required Variables
        public Socket socket;
        public int index;
        private byte[] dataBuffer = new byte[0x400];
        private AsyncCallback ReceiveCallback;
        private AsyncCallback SendCallback;
        #endregion

        #region ArchiCruise Vars
        public ArchiCruise.Users.UserObject userObject;
        public string ip;
        #endregion

        public TcpClient(Socket sock, int num)
        {
            index = num;
            socket = sock;

            ip = socket.RemoteEndPoint.ToString().Split(new char[] { ':' })[0];

            ReceiveCallback = new AsyncCallback(this.ReceivedData);
            SendCallback = new AsyncCallback(this.sentData);

            this.WaitForData();
        }

        public void Disconnect()
        {
            if (socket.Connected)
            {
                socket.Close();
                if (userObject != null) userObject.remove();
                Particle.Server.removeClient(this);
                Log.Info("Client" + this.index + " disconnected and removed.");
                Console.WriteLine("Client" + this.index + " disconnected.");
            }
        }

        private void ReceivedData(IAsyncResult iAr)
        {
            try
            {
                int count = 0;

                try
                {
                    count = socket.EndReceive(iAr);
                }
                catch
                {
                    Disconnect();
                }

                StringBuilder builder = new StringBuilder();
                builder.Append(System.Text.Encoding.Default.GetString(this.dataBuffer, 0, count));
                string str = System.Text.Encoding.Default.GetString(this.dataBuffer, 0, count);

                if (str.Contains("<policy-file-requet/>"))
                {
                    Log.Info("Sending policy file to client" + this.index);
                    rawSend("<?xml version\"1.0\"?><cross-domain-policy><allow-access-from-domain=\"*\" to-ports=\"*\" /><cross-domain-policy>" + Convert.ToChar(0));
                }
                else if (!(str.ToString() == ""))
                {
                    string packet = str.Substring(0, str.Length - 1);
                    //packet = ArchiCruise.Security.Encryption.decrypt(packet);
                    Log.Info("Got " + str + " from client " + this.index);

                    Particle.packetClass.handle(packet, this);
                }
                else
                {
                    Disconnect();
                }
            }
            catch (Exception exception)
            {
                Log.Info("Data recieve error: " + exception.ToString() + " " + exception.Source);
                Disconnect();
            }
            finally
            {
                this.WaitForData();
            }
        }

        private void WaitForData()
        {
            try
            {
                socket.BeginReceive(this.dataBuffer, 0, this.dataBuffer.Length, SocketFlags.None, this.ReceiveCallback, socket);
            }
            catch
            {
                Disconnect();
            }
        }

        public void sendData(string Data)
        {
            Data += (char)1;
            rawSend(Data);
        }

        internal void rawSend(string Data)
        {
            try
            {
                Data += "\0";
                byte[] bytes = System.Text.Encoding.Default.GetBytes(Data);

                socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(this.sentData), null);
                Log.Info("Sent " + Data + " to client " + this.index);
            }
            catch
            {
                Disconnect();
            }
        }

        private void sentData(IAsyncResult iAr)
        {
            try
            {
                socket.EndSend(iAr);
            }
            catch
            {
                Disconnect();
            }
        }
    }
}

Adobe Flash/ActionScript 3.0 moving to next scene but nothing plays

I've searched endlessly for an answer but can't seem to find one.

I'm building a flash presentation for a client. It's got about 15 scenes, the .fla file is 200MB before publishing (26MB afterward). It's a pretty simple operation; I'have a pause/play & replay button, and once the scene is completed a next & replay button appears in the center of the stage.

My issue is when I get to about the 8th scene, halfway through. All my tweens and buttons stop working. Simple fade-in text doesn't come up and my pause/play & replay no longer function. I've tried shifting around scenes to see if it was anything in particular, but no matter what order and what scenes it always stops halfway through the 8th. I don't get any error notifications before, after or during the play. Tracing tells me that the button has been clicked and it's moved to the next scene but it simply will not play. Adding a play(); comment at the first frame of the next scene has not helped either.

Here are my functions that are on Scene 1 Frame 1

function pause_movie(event:MouseEvent):void {
    stop();
    playBtn.visible = true;
    pauseBtn.visible = false;
}

function play_movie(event:MouseEvent):void {
   play();
   playBtn.visible = false;
   pauseBtn.visible = true;
}

function replay_movie(event:MouseEvent):void {
   gotoAndPlay(1);
}

function next_movie(event:MouseEvent):void {
    this.nextScene();
    trace("next_movie " + this.currentScene.name);
}

And then I just add event listeners when my buttons appear per scene

import flash.events.MouseEvent;

//Hide play button to start
playBtn.enabled = true;
pauseBtn.enabled = true;
playBtn.visible = false;

pauseBtn.addEventListener(MouseEvent.CLICK, pause_movie);
playBtn.addEventListener(MouseEvent.CLICK, play_movie);
replayBtn.addEventListener(MouseEvent.CLICK, replay_movie);

Any help is appreciated! Thank you!

AS3 embedded fonts inside swfs loaded into application sandbox - odd behaviour

I'm seeing some very mysterious font behaviour in AS3, Air App, using Flash version 11.5, compiling my fla files in Flash Pro CC 2014.

Context: Air application, shell loads swfs at runtime as 'modules', into the application domain (so they are run as if they were part of the main app, not as children inside a sandbox).

Problem: Some dynamic textfields containing embedded fonts in some of the loaded swfs are not appearing, while others are fine.

Details:

  • This is a new problem - fonts that were fine a few weeks ago are now misbehaving. (Same computer, same OS and Flash version)

  • The same font that is missing in some 'modules' (swfs) is present in others.

  • Some fonts from the same family work everywhere (Myriad Pro Semibold), others are missing in some places, but present in others (Myriad Pro Regular)

  • All the TextFields are inside movieclips that are then pulled in to the swfs at compile time using

[Embed(source="someFla.swf", symbol="libraryExportName")]

  • The Air 'shell' contains and successfully uses Myriad Pro Semi, Myriad Pro Regular and Arial. (Only)
  • Some fonts appear fine locally during test, but then disappear once the Air app is installed (Myriad Pro Regular)
  • Other fonts are consistently rubbish - Helvetica Neue for example, disappeared in multiple places in test as well as once installed
  • All the fonts are embedded as required in the individual swfs (Basic Latin set) but not exported for actionscript as the fonts are set at compile time rather than at run time.

If anyone has any insights or suggestions that would be great. My hunch is that the fonts that are embedded into multiple swfs are somehow 'clashing', but I can't unravel why I get some clashes while others are fine. I've wrangled font embedding in flash for many years and I've tried everything I can think of to overcome the usual gotchas.

How to pass variable from MySQL to SWF

I am trying to pass an ssoTicket from MySQL through a webpage and into a SWF file.

The bellow code results in null in the server log, but when I set an ssoTicket that matches, everything works fine.

There seems to be relatively little information online.

I have printed sso_ticket and it does echo the correct string.

Page

var flashvars = {
    sso: "<?php echo $self['sso_ticket']; ?>" 
};

SWF

var ssoTicket:String = LoaderInfo(this.root.loaderInfo).parameters["sso"];

SWF With pre-set ssoTicket

var ssoTicket:String = LoaderInfo(this.root.loaderInfo).parameters["sso"];          
if (ssoTicket == "" || ssoTicket == null) ssoTicket = "73a448e7e4a3314d2d1a3f33588df9b8";

samedi 30 janvier 2016

Stage3DProxy in a Worker

I'm attempting to put an Away3d in a worker to separate the 3D and the UI and reduce performance lag on mobile.

As soon as the Away3D attempts to get a free proxy

stage3DProxy = stage3DManager.getFreeStage3DProxy();

I get the error

Too many Stage3D instances used!
    at away3d.core.managers::Stage3DManager/getFreeStage3DProxy()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\managers\Stage3DManager.as:98]
    at away3d.containers::View3D/onAddedToStage()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\containers\View3D.as:931]
    at flash.display::DisplayObjectContainer/addChild()

Does anyone know if there are issues with loading Stage3D in a Worker?

AS3 Workers - ReferenceError: Error #1065: Variable PanoWorker is not defined

Hi I'm getting this error when I attempt to create a worker using

http://ift.tt/1nvntca

ReferenceError: Error #1065: Variable PanoWorker is not defined

From

var panoWorker:Worker = WorkerFactory.getWorkerFromClass(PanoWorker, loaderInfo.bytes);
            panoWorker.start();

The PanoWorker Class

package co.beek.workers.panoWorker
{
import flash.display.Sprite;
import flash.system.Worker;

import co.beek.pano.Pano;


public class PanoWorker extends Sprite
{
    public function PanoWorker()
    {
        super();
        trace("Hello from the Worker!");
        trace("isPrimordial: " + Worker.current.isPrimordial)


        var pano:Pano = new Pano;

        addChildAt(pano,0);
        //var life:MyClass = new MyClass;
        //trace("Meaning of life is: " + life.meaning);
    }
}
}

I just can't work out where the problem is coming from, debugger isn't giving me a lot of help.

Compiler Error: 1046: Type was not found or was not a compile-time constant: Stage

I keep getting the 1046 error. Here's the code:

package  {

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

public class MainDocument extends MovieClip {

    private var login:Login;

    public static var STAGE:Stage;
    public static var doc:MainDocument; //needed to easily use methods in other classes


    public function MainDocument() {
        // constructor code
        trace("Main Document is here");
        STAGE = stage;
        doc = this;
        // Set up listeners for UI login and register buttons
        selectLogin_btn.addEventListener(MouseEvent.MOUSE_UP,showLogin);
        selectRegister_btn.addEventListener(MouseEvent.MOUSE_UP,showRegister);
    } // end function

    private function showLogin(e:MouseEvent):void{
        trace("Login button is pressed");
        login = new Login();
        login.x = 272;
        login.y = 183;

        addChild(login);
        login.name = "Login";
        STAGE.focus = login.login_txt;
        showMsg("");
    } // end function 

    private function showRegister(e:MouseEvent):void{
        trace("Register button is pressed");
    } // end function

    public function showMsg(s:String):void{
        welcome_txt.text = s;
    } // end function

} // end class

} // end package

The error shows up on this line:

public static var STAGE:Stage;

Here's the error:

1046: Type was not found or was not a compile-time constant: Stage.

Any help would be greatly appreciated.

Flex/Actionscript - "class" XML attribute name error when parsing to ArrayCollection

I am trying to convert XML response event to ArrayCollection using Flex 4 and Actionscript the problem being that I don't have control on the output XML HTTP response and one of the attributes is names 'class' so I get an error trying to access the object

Actionscript code;

protected var products:ArrayCollection;

protected function service_resultHandler(event:ResultEvent):void { products = event.result.oxip.response.class.type.market; }

I have main swf and I load external swf to stage. I need to access sounds or a mc within external swf

The reason why I need this is; I will have one main swf and External 50 swfs which are small games. Within the games I have buttons and Sounds. Because of These buttons and sounds are same, I want to put them to main swf and call from external swfs. One reason is the lower file size, the other reason if I want to change the color of button or sound, I will just change from main swf. make them change at same time.

Let say main swf.

var snd:Sound = new snd_true();

External swf

var channel:SoundChannel = new SoundChannel();
channel = snd.play(50);
channel.soundTransform = new SoundTransform(1);

Or At the main swf at the library I have mc and want to use on my external swf with addchild funtion.

Thanks in advance.

Radial Gravity For A Planet Object In A Platformer Game And Its Class Structure

I am currently helping to make a game as a part of a Group Project at my University Games course using Action Script 3 within Flash Develop (we have the option to use other software such as Unity etc.).

The game we are developing will be a traditional platformer game, except instead of moving from left to right the complete each level, the player must reach the centre of the circular level, or planet.

I have two problems with this:

1) An actual solution for drawing in all objects towards the centre of the screen constantly (which stems from the problem of:)

2) The correct way to layout the classes and how each one is used.

We have been taught basic knowledge of different features of the program, such as using timers, input devices, listen events etc. but we have not been taught anything on basic class structure and I am having trouble starting off. (Classes for menu's, levels, NPC/enemies that spawn multiple instances etc.)

I am not asking for exact code to create something as such, I just need to know how to formulate the basic class structure for such a game for it to work correctly and perhaps the general idea of achieving radial gravity, as I it would be great if I could start this off with only a nudge in the right direction and figure the rest out on my own.

How to change as3 code in a class file

I am working on some jigsaw puzzles for children on the iPad.

This code is working fine for 3 puzzles, but it is a lot of code that i repeat and i am wondering how to change the code so it will be possible to use a class file. Hope someone can help me with this.

var puzzel1:Array = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16];
var puzzel1k:Array = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16];

for each(var current_piece:MovieClip in puzzel1){
    current_piece.visible = true;
    current_piece.addEventListener(MouseEvent.MOUSE_DOWN, drag_piece_puzzel1);
    current_piece.addEventListener(MouseEvent.MOUSE_UP, stop_piece_puzzel1);
}

for each(var target_piece:MovieClip in puzzel1k){
    target_piece.visible = true;
}

//alle pieces van puzzel 1 worden hiermee gedragd
function drag_piece_puzzel1(e: MouseEvent): void {
    current_piece = MovieClip(e.currentTarget);
    current_piece.startDrag();
    current_piece.scaleX = 0.85;
    current_piece.scaleY = 0.85;
    addChild(current_piece);
    if(current_piece == p1){target_piece = t1;}
    if(current_piece == p2){target_piece = t2;}
    if(current_piece == p3){target_piece = t3;}
    if(current_piece == p4){target_piece = t4;}
    if(current_piece == p5){target_piece = t5;}
    if(current_piece == p6){target_piece = t6;}
    if(current_piece == p7){target_piece = t7;}
    if(current_piece == p8){target_piece = t8;}
    if(current_piece == p9){target_piece = t9;}
    if(current_piece == p10){target_piece = t10;}
    if(current_piece == p11){target_piece = t11;}
    if(current_piece == p12){target_piece = t12;}
    if(current_piece == p13){target_piece = t13;}
    if(current_piece == p14){target_piece = t14;}
    if(current_piece == p15){target_piece = t15;}
    if(current_piece == p16){target_piece = t16;}
}



function stop_piece_puzzel1(e: MouseEvent): void {

    current_piece.stopDrag();

    if (target_piece.hitTestObject(current_piece)) {
        current_piece.scaleX = 1;
        current_piece.scaleY = 1;
        current_piece.x = target_piece.x;           
        current_piece.y = target_piece.y;
        if (array_pieces.indexOf(current_piece) == -1) {
            counter = counter +1;
            puzzlepiece = current_piece;
            array_pieces.push(this["puzzlepiece"]);
            }
    }
}

Keep them spread out?

Sorry if the title is ambiguous, I don't know how to really word what I'm trying to do.

So, anyway, I've created a basic zombie game where green squares follow you, you can die and kill the zombies.

The problem is, if there's a large crowd of the zombies, they all go into eachother and make one square, seeing as collision is too hard to do since they're moving along where they're pointing (pointing at the player), is there a way I can keep them spread out enough so they never go into eachother?

here's the code where I move the zombies:

        for (var i2:int; i2 < ZombiesOnScreen.length; i2++ )
        {
            if (ZombiesOnScreen[i2].alive == true)
            {
                var dist_Y2:Number = player.y - ZombiesOnScreen[i2].y;
                var dist_X2:Number = player.x - ZombiesOnScreen[i2].x;
                var angle2:Number = Math.atan2(dist_Y2, dist_X2);
                var degrees2:Number = angle2 * 180 / Math.PI;
                ZombiesOnScreen[i2].rotation = degrees2;
                var zomBAngle:Number = ZombiesOnScreen[i2].rotation * Math.PI / 180;
                ZombiesOnScreen[i2].x = ZombiesOnScreen[i2].x + 1.6 * Math.cos(zomBAngle);
                ZombiesOnScreen[i2].y = ZombiesOnScreen[i2].y + 1.6 * Math.sin(zomBAngle);
            }
            if (ZombiesOnScreen[i2].hitTestObject(player))
            {
                gameOver();
            }
        }

Also, sorry if this is literally just collision but just spaced out, I just want a way to stop them merging.

vendredi 29 janvier 2016

Multithreding in flex web application

I am working on web application. In which i am stuck with some issue.

When i call some server function it will take time to get response. When response have high number of data. It will get data, process on that data and update GUI in background.

Upto that My application GUI freeze. I can not click on any part. I see some where that ActionScript support multithreading. I found some tutorial for that which is here. But, it is for desktop application only.

Is there any way i can handle this freezing of application/GUI in web application. It will decrease my application performance and looks very bad.

Any help is greatly appreciated.

ActionScript 3.0 - Bouncing off edges not working

I am trying to make a replica of the old Pong in AS3 and i wanna make my ball bounce when it touches the edges but all my code does is making the ball go crazy. I fail to see why and that's why i'm asking for help.

ball.x = ball.x + xSpeed;
ball.y = ball.y + ySpeed;

if(ball.x - ball.width /2 <= 0)
{
    xSpeed = xSpeed * -1;
}
if(ball.x + ball.width / 2 >= stage.width)
{
    xSpeed = xSpeed * -1;
}


if(ball.y - ball.height / 2 <= 0)
{
    ySpeed = ySpeed * -1;
}
if(ball.y + ball.height / 2 >= stage.height)
{
    ySpeed = ySpeed * -1;
}

x and y are in the center of the ball object.

Tweeting effect for scrolling list in AS3 Flex

I have a canvas called tileListCanvas which I scroll through vertically when the mouse moves up and down over the tileListCanvas. Everything is working fine but I would like to add a tween effect to the scrolling behaviour so that scrolling slows down gradually and comes to a stop when the user stops moving the mouse. The scrolling behaviour is implemented by target = tileListCanvas.verticalScrollPosition -= (10 - yDiff) for scrolling up and target = tileListCanvas.verticalScrollPosition += (10 + yDiff) for scrolling down.

If anyone can give me some idea of how this can be done it would make my day!

[Bindable]private var previousX:Number = 0;
            [Bindable]private var previousY:Number = 0;
            [Bindable]private var currentX:Number = 0;
            [Bindable]private var currentY:Number = 0;
            [Bindable]private var xDir:String;
            [Bindable]private var yDir:String;
            [Bindable]private var xDiff:Number = 0;
            [Bindable]private var yDiff:Number = 0;

            [Bindable]private var lastX:Number = 0;
            [Bindable]private var lastY:Number = 0;
            [Bindable]private var speed:Number;
            [Bindable]private var target:Number = 0;

            private function initMouseDirectionChecker():void
            {
                tileList.addEventListener(MouseEvent.MOUSE_MOVE, checkDirection);
            }



            private function beginScrolling(mouseEvent:MouseEvent):void
            {
                tileListCanvas.verticalScrollPosition -= 5;
            }

             public function checkDirection(e:MouseEvent):void
            {
                getHorizontalDirection();
                getVerticalDirection();

                dir1.text = "x: " + xDir
                dir2.text = "y: " + yDir;
            }

            //Horizontal
            private function getHorizontalDirection():void
            {
                previousX = currentX; //Checks the last position
                currentX = stage.mouseX; //Gets the current position

                if (previousX > currentX) //Compares both positions to determine the direction
                {
                    xDir = "left";
                }
                else if (previousX < currentX)
                {
                    xDir = "right";
                }
                else
                {
                    xDir = "none";
                }
            }

            //Vertical
            private function getVerticalDirection():void
            {
                previousY = currentY; //Checks the last position
                currentY = stage.mouseY; //Gets the current position

                if (previousY > currentY) //Compares both positions to determine the direction
                {
                    yDir = "up";
                    target = tileListCanvas.verticalScrollPosition -= (10 - yDiff);                 
                }
                else if (previousY < currentY)
                {
                    yDir = "down";
                    target = tileListCanvas.verticalScrollPosition += (10 + yDiff);
                }
                else
                {
                    yDir = "none";
                }
            }

Stop them from merging into eachother?

I'm creating a simple zombie game in AS3 where zombies (represented by 25x25 squares) go towards your mouse

at the moment it works, but the main problem is when they're moving towards your mouse, they will soon merge into eachother and look like one rectangle. I want them always spaced out.

Here's my code for rotating and then moving the zombies towards the mouse:

private function update(e:Event = null):void
{
    for (var i2:int; i2 < ZombiesOnScreen.length; i2++)
    {
        var dist_Y:Number = stage.mouseY - ZombiesOnScreen[i2].y;
        var dist_X:Number = stage.mouseX - ZombiesOnScreen[i2].x;
        var angle:Number = Math.atan2(dist_Y, dist_X);
        var degrees:Number = angle * 180 / Math.PI;
        ZombiesOnScreen[i2].rotation = degrees;
        trace(ZombiesOnScreen[i2].rotation)
        var zomBAngle:Number = ZombiesOnScreen[i2].rotation * Math.PI / 180;
        ZombiesOnScreen[i2].x = ZombiesOnScreen[i2].x + 5 * Math.cos(zomBAngle);
        ZombiesOnScreen[i2].y = ZombiesOnScreen[i2].y + 5 * Math.sin(zomBAngle);

    }
}

ActionScript 3 - Saving Shape graphic into XML format

As AS3 doesn't support saving Shape objects into SharedObjects I'm in need of a way of saving Shape objects into .xml format so that these graphics can be recovered as and when needed. I know how to create and save an .xml file but need help with how to populate the .xml file with the Shape.

tweening multiple objects, calling on complete only once

I am tweening multiple items in array.But I want onComplete be called only once. Is there way to write it more readable?

for (var i : int = 0; i < _cardsToRollOut.length; i++)
{   
            var wCard : TacticCard = _cardsToRollOut[i];

            if (doItOnce) TweenMax.to(wCard, 0.5, { delay:1, rotation:firstRotation + 0.4 * i} );
            else
            {
                doItOnce = true;
                TweenMax.to(wCard, 0.5, { delay:1, rotation:firstRotation + 0.4 * i, onComplete:updateCounters } ); 
            }
}

Thank you in advance!

Adobe AIR, Native Extension load only specific device

I've got a native extension for Android. The functionality of this native extension is already implemented in the Air SDK for iOS. So I use the SDK functions on iOS and the native extension for Android.

The native extension doesn't support iOS, which makes sense, because the functionality is already implementent in the Air SDK for iOS.

When I start the App on Android everything works fine. But if I start the App on iOS I got the following error

VerifyError: Error #1014: Class com.afterisk.shared.ane.lib::GCMEvent could not be found

I splitted the code for each device in different classes. But it seems that Air try to compile the code for Android anyway.

Are there any way to prevent this behavior?

Sort on datagrid also sort null values in flex

Today i am getting some weird issue in datagrid.

<s:DataGrid id="grid_result" dataProvider="{somelist}" sortableColumns="true">

I have datagrid and on top header click it sort the column suppose this is the column.

<s:GridColumn headerText="Temp" dataField="tempName">

It will display tempName from someList. But some of data is null. So, when i sort this column on header of this column click it will sort null value also.

like it display:

A
B
.
.
l
m
blank cell
blank cell
o
p
.
.
Z

It consider null value after m and before o. I think it consider null as n(I may wrong for this).

I want to display null value at last. I have search lot but not found any solution.

Any help is greatly appreciated.

jeudi 28 janvier 2016

Do you know if it's possible to use Google Maps in AIR with feathers-maps?

I discovered this on GitHub and I was wondering if it was possible to use it in Adobe Flash Pro CC for creating an AIR app with Google map.

I've tried to import to the library both of the swc file and copy the code "Basic maps usage". But it won't work. Any idea if it's possible ?

http://ift.tt/1Uus8pv

How do I get the list of images in a specific folder CameraRoll. To load in my application

I am developing an application in AIR / AS3 and do not want to use the native Device image selection screen, must receive the list to create thumbnails within my application (Ex: Instagram). Help me please

Flash AS3 API deprecation

Recently I was working with the Flash AS3 YouTube api when this message came up in my output window:

The YouTube AS3 Player API will be disabled on January 27, 2016. See http://ift.tt/1ha31aO

Today is January 28th, 2016 and my AS3 YouTube embed Flash creative still works as expected. Did this deadline get extended? If so for how long?

Anyone with information around this would be greatly appreciated. Thanks!

Pointing towards mouse AS3

So, I followed this tutorial on creating dynamic shadow engine in AS3. I've done and completed it, but I have a problem.

I want to point one of the shapes towards a point (eg: mouse position), the problem is that the function that rotates it doesn't point it towards a point (it's only used to keep on rotating something like this)

I have no idea how to change it so it can point towards the mouse (or if you even need to change the function itself)

here's the rotate function and everything related to it:

public function applyVerticesRotation(rotationAngle:Number):void
{
    _iterator = 0;

    while (_iterator < _numberOfVertices)
    {
        _vertices[_iterator] = rotatePoint(_vertices[_iterator], rotationAngle);

        _iterator++;
    }
}

private function rotatePoint(point:Point, angleRadians:Number):Point
{
    var tempX:Number = point.x * Math.cos(angleRadians) - point.y * Math.sin(angleRadians);
    var tempY:Number = point.x * Math.sin(angleRadians) + point.y * Math.cos(angleRadians);

    return new Point(tempX, tempY);
}

Also, here's how I'm trying to point it towards the mouse (they're defined as private variables at the start of the code):

    dist_Y =stage.mouseY -this._randomShape.y ;
    dist_X =stage.mouseX -this._randomShape.x ;
    angle = Math.atan2(dist_Y,dist_X);
    degrees = angle * 180 / Math.PI;

Sorry if the solution is obvious, I'm decently new to AS3.

create pages when too much text in an array

I've got this code for my AIR app that creates pages when the list of word (product) is too long. When there are more than 11 products, it creates a new page. I can then click on the next button to see the 11 newt products.

I've also put a search bar that search words in the array and display them.

Problem : I can't make the same logic with the result of the search and I don't know why but I cant create "pages" with the result. Any idea how I can do that ?

Here's my code for creating pages if too much item :

const itemsPerPage:uint = 10;

 var currentPageIndex:int = 0;

 function displayPage(pageIndex:int):void {
 list.removeChildren();
 currentPageIndex = pageIndex;
 var firstItemIndex:int = pageIndex * itemsPerPage;
 var j:int = 0;
 var lastItemIndex: int = firstItemIndex + 10; // as lastItemIndex should be 10 more
 if (lastItemIndex > products.length) // if lastindex is greater than products length
 lastItemIndex = products.length;
 for(var i:int = firstItemIndex; i< lastItemIndex; i++){
 createListItem( j, products[i]); // j control the position and i points to particular element of array..
 j++;
 }


 next.visible = lastItemIndex = 0; i++, l--){
 createListItem(i, products[l]);
 }
 displayPage(0);
 showList();
 }


 next.addEventListener(MouseEvent.CLICK, nextClick);
 previous.addEventListener(MouseEvent.CLICK, previousClick);

 function nextClick(e:MouseEvent):void {

 trace(currentPageIndex);
 displayPage(currentPageIndex + 1);
 previous.visible=true;
 }
 function previousClick(e:MouseEvent):void {
 if(currentPageIndex==0){
 previous.visible=false;
 }else{
 displayPage(currentPageIndex - 1);
 }
 }

And here's my search code:

function onClick(event:MouseEvent){

 var toMatch:String = searchBar.text.toLowerCase();

 addChild(list);
 if (contains(list)){
 list.removeChildren();

 }
 else 
 {

 }
 var j:int =0; 

 for(var i:int = 0, l:int = products.length - 1; l >= 0; i++, l--){//variable that store search result only
 //applying logic a.indexOf("world") >= 0
 if(products[i].title.toLowerCase().indexOf(toMatch)>= 0)
 {
 j++;
 createListItem(j, products[i]); 
 }
 else {
 trace("no result");
 }
 }

 }

How can I apply the same logic to the result of the search ?

Method setSelectedIndex for ComboBox in Flex 4/ActionScript 3: is there any current documentation?

I've been looking at Adobe's documentation for the spark ComboBox, but I'm not able to find the method:

setSelectedIndex(value:int, dispatchChangeEvent:Boolean = false, changeCaret:Boolean = true):void

I know this function exists, because my code uses it. I'm using Flex sdk 4.14.1. When I go to the ComboBox.as source file, I find the function well and good:

/**
 *  @copy spark.components.supportClasses.ListBase#setSelectedIndex()
 *  
 *  @langversion 3.0
 *  @playerversion Flash 11.1
 *  @playerversion AIR 3.4
 *  @productversion Flex 4.10
 */
override public function setSelectedIndex(value:int, dispatchChangeEvent:Boolean = false, changeCaret:Boolean = true):void
{
    // It is possible that the label display changed but the selection didn't.  If this is
    // the case, the label has to be updated since the setSelectedIndex code will short-circuit
    // and not commit the selection.
    // An example is if the label is deleted and then the first item is chosen from the
    // dropdown, the selectedIndex is still 0.
    if (userTypedIntoText && value == selectedIndex)
        updateLabelDisplay();

    super.setSelectedIndex(value, dispatchChangeEvent, changeCaret);
}

I also went up the inheritance tree (DropDownListBase -> List -> ListBase etc) and none of the classes that ComboBox inherits from have documentation on setSelectedIndex.

The only documentation I could find was an old version (Flex 4.10) saved on ZengRong's blog.

Is the method setSelectedIndex still supported? Is there anywhere else I could look for documentation?

Cloning object (Drag and drop) Flash As3

How do I make a clone of a movieclip after it has been dragged, and make the clone appear where the dragged movieclip was before being dragged?

This is what I have so far:

movieClip_1.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_2);

function fl_ClickToDrag_2(event:MouseEvent):void
{
movieClip_1.startDrag();
}

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_2);

function fl_ReleaseToDrop_2(event:MouseEvent):void
{
movieClip_1.stopDrag();
}

Also I would also like to know how to make a reset button, to reset the dragged and dropped objects on stage

Here is an example I found, with similar functions

https://dl.dropboxusercontent.com/u/418650/hype/08_Using_5_Frames.swf

Using action script 3 with flash builder 4.7 when i try to load image of dimension 16000 X 16000, not able to upload

I found below problem in action script 3.

Using action script 3 with flash builder 4.7 when i try to load image of dimension 16000 X 16000 using below code it will CRASH my App and not able to show image.

Image size is 4.6 MB and Image dimension is 16000 X 16000 (Width X Height)

When i try with other image having Dimension 10000 X 3000 (Width X Height) it will work

var mapLoader:Loader=new Loader();
var loaderInfo:LoaderInfo=mapLoader.contentLoaderInfo;      

loaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void
            {
            var image:Image=new Image();
            image.source=mapLoader.content;
            image.width=image.source.width * 0.6; 
            image.height=image.source.height * 0.6;             
            image.smooth=true; 
            }
            });
            loaderInfo.addEventListener(IOErrorEvent.IO_ERROR,function(e:IOErrorEvent):void
            {
                //some code
            });         
            mapLoader.load(new URLRequest(mapSrc));

Please help me and thanks in advance

mercredi 27 janvier 2016

Converting Keyboard Event to Touch/Press Event for Android Game

I am developing an android game using Flash CS6 and AS 3.0. What I want to achieve is to convert keyboard events to touch/press events for it to be working on a mobile device.

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

public class Game extends MovieClip
{
    public var army:Array;
    public var enemy:Enemy;
    public var avatar:Avatar;
    public var useMouseControl:Boolean;
    public var leftKeyIsBeingPressed:Boolean;
    public var rightKeyIsBeingPressed:Boolean;

    public function Game()
    {
            leftKeyIsBeingPressed = false;
            rightKeyIsBeingPressed = false;

            if ( useMouseControl )
            {
                    avatar.x = mouseX;
                    avatar.y = mouseY;
            }
            else
            {
                    avatar.x = 240;
                    avatar.y = 600;
            }

            addEventListener( Event.ADDED_TO_STAGE, onAddToStage );
    }

    public function onAddToStage( event:Event ):void
    {
        stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
        stage.addEventListener( KeyboardEvent.KEY_UP, onKeyRelease );
    }

    public function onKeyPress( keyboardEvent:KeyboardEvent ):void
    {
        if ( keyboardEvent.keyCode == Keyboard.LEFT )
        {
            leftKeyIsBeingPressed = true;
        }
        else if ( keyboardEvent.keyCode == Keyboard.RIGHT )
        {
            rightKeyIsBeingPressed = true;
        }
    }

    public function onKeyRelease( keyboardEvent:KeyboardEvent ):void
    {
        if ( keyboardEvent.keyCode == Keyboard.LEFT )
        {
            leftKeyIsBeingPressed = false;
        }
        else if ( keyboardEvent.keyCode == Keyboard.RIGHT )
        {
            rightKeyIsBeingPressed = false;
        }
    }

I removed unnecessary codes but it is working using keyboard and I am really struggling how to use a touch/press event. Need help asap.

Sprite Object in Action script

I have a action script which send requests to a web server with image data. Here is the script:

import flash.events.MouseEvent;
import flash.display.MovieClip;
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.net.URLLoader;
import mx.utils.Base64Encoder;
import flash.external.ExternalInterface

for (var i=1; i<27; i++)
{

    this["object" + i].buttonMode = true;
    this["object" + i].addEventListener(MouseEvent.CLICK, mouseClickEvent);

}

function mouseClickEvent(e:MouseEvent):void {


        var objectClass: Class = getDefinitionByName(getQualifiedClassName(e.currentTarget)) as Class;

        var copy: MovieClip = new objectClass();
        copy.name = "copy"; //This is newly added
        this.addChild(copy);
        copy.x = 300;
        copy.y = 200;


        copy.addEventListener(MouseEvent.MOUSE_DOWN, onStart);
        copy.addEventListener(MouseEvent.MOUSE_UP, onStop);


    var sx:Number;
    var sy:Number;      
    sendSprite(Sprite(this),"http://localhost/flash/image.php");

    //ExternalInterface.call("myf", "Test");

function onStart(e)
{
    e.currentTarget.startDrag(true);
    copy.x = e.currentTarget.x;
    copy.y = e.currentTarget.y;
    e.currentTarget.startDrag();
}
function onStop(e)
{ //copy.hitTestObject(trash)
    if(copy.x<=40) 
    {
    removeChild(copy);
    }

e.currentTarget.stopDrag();     
sendSprite(Sprite(this),"http://localhost/flash/image.php");

}


        copy.doubleClickEnabled=true; 
        copy.addEventListener(MouseEvent.DOUBLE_CLICK, rotateCW);

function rotateCW(event:MouseEvent):void{
        copy.rotation += 90;

    }

}

        clear_mc.addEventListener(MouseEvent.CLICK, linkToPage);

function linkToPage(e:MouseEvent):void{
    var request:URLRequest = new URLRequest("http://ift.tt/1NCoPab");
    navigateToURL(request);
}
function sendSprite(sprite: *, scriptLocation: String): void {
        var bmpData: BitmapData = new BitmapData(1024, 768, true, 0xFFFFFF);
        bmpData.draw(sprite);

        var encodedFile: Base64Encoder = new Base64Encoder();
        encodedFile.encodeBytes(PNGEncoder.encode(bmpData));

        var data: URLVariables = new URLVariables();
        data.fileData = encodedFile;

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

        var loader: URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, spriteSend);
        loader.addEventListener(Event.OPEN, traceEvent);
        loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, traceEvent);
        loader.addEventListener(IOErrorEvent.IO_ERROR, traceEvent);
        loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, traceEvent);
        loader.addEventListener(ProgressEvent.PROGRESS, traceEvent);

        try {
            loader.load(request);
        } catch (e: * ) {
            trace("an error occured of type", e);
        }

        function traceEvent(e: * ): void {
            trace(e);
        }

        function spriteSend(e: Event): void {
            trace(e, "\n sprite succesfully send \n");
        }

}   

I am able to send request when any new object is added. However I am getting an error while sending the same request in onStop event. Please advise.

Removing event listeners when replaying Flash movie

Just to give you a preface, I started messing with event handlers to fix a jerky animation transition when jumping from one set of looped frames to another all within the same time line.

Ok, let's say I have an animation of a horse running consisting of 5 frames. Now let's say I have three different movie clip loops of these frames at different speeds (different fps really): walk, trot, and gallop.

Now let's say I've created a button that lets the viewer progress through each set of loops and then another to let them replay back from the beginning. My initial problem arose when jumping from say the first loop (1-5) to the next loop (6-10) because essentially at any point when hitting that forward button I'm stopping the loop and starting it again from the beginning. Hence the hiccup in the animation.

To combat this I found an example online where you can use an event listener to check what frame you're at when the button is pushed then lets it complete the loop and then move on, thus negating any weird flinch.

Here's that event code:

forward1.addEventListener(MouseEvent.CLICK, trot); 

function trot(event: MouseEvent): void { 

addEventListener(Event.ENTER_FRAME, enterFrame); 
function enterFrame(e:Event):void { 
    if (currentFrame == 5) { 
        gotoAndPlay(6); } 

    } 
}

Meanwhile the next one would look like this:

forward2.addEventListener(MouseEvent.CLICK, gallop); 

function gallop(event: MouseEvent): void { 

addEventListener(Event.ENTER_FRAME, enterFrame); 
function enterFrame(e:Event):void { 
    if (currentFrame == 10) { 
        gotoAndPlay(11); } 

    } 
}

I don't know if it's important btw, but I'm creating my loops on the very last frame of each group and sending it back to the first frame (of that group).

So, I've got on of those listeners on buttons at each set of loops and it plays through great...the first time. Here's where my current issue comes in. When getting to the very end of the movie I've got this:

playagain.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndPlayFromFrame_1);

function fl_ClickToGoToAndPlayFromFrame_1(event:MouseEvent):void
{
    gotoAndPlay(1);
}

Which basically just takes the playhead back to the first frame on click. BUT, now instead of waiting for the user to click to forward the animation to the second loop set, the movie just auto plays through the entire thing.

My assumption is that the event listeners from the first play-through are still there and running. So, essentially Flash is seeing "Hey when you get to frame X go on to frame Y" "When you get to frame Y go to frame Z" and so on.

How do I remove those listeners after they've fired? Can I remove them all at once before the replay?

Or, is there a better way to check where the playhead is when jumping between two sets of loops, finishing whatever loop it's on before going where I tell it to?

ActionScript game, having trouble implementing decorator class

So, I've created a tile based "match 3" game in ActionScript and there are a few different types of tiles the main tiles are just letter tiles, and then there are special tiles like a bomb for instance and each tile has similar functionality but each one has special functionality.

Right now, I just have a Tile class that handles all of the functionality which is not the way to go. I think a decorator class would be the best route however implementing it, i am running into issues.

So below is how I have it structured, how would I handle storing the tiles in a Vector? and how would I add to stage?

Currently, I store the tiles in a Vector.(I have one Tile class that handles all of the type types which is ugly). If I were to move to a decorator pattern, it seems that I would be storing a Vector of ITile, how would I add "Itiles" which are essentially LetterTiles and BombTiles to stage? I get Type Coercion errors when trying.

Also, the decorator pattern just seems to be basically an interface, which all types would just implement, so for example, if I were to take an existing LetterTile on stage and say it needs to convert to a BombTile, How would I go about changing or updating the current tile into a Bomb tile?

example:

public interface ITile
{
    function create():void;
    function remove():void;
}

and BaseTile.as

public class BaseTile extends Sprite
{
    public function create():void
    {
        throw new IllegalOperationError("Must override in concrete class");
    }

    public class remove():void
    {
        throw new IllegalOperationError("Must override in concrete class");
    }
}

LetterTile.as

public class LetterTile extends BaseTile implements ITile
{
    public override function create():void
    {
        trace("Letter Tile Created");
    }

    public override function remove():void
    {
        trace("Letter Tile Removed");
    }
}

BombTile.as

public class BombTile extends BaseTile implements ITile
{
    public override function create():void
    {
        trace('Bomb tile created');
    }

    public override function remove():void
    {
        trace('Bomb tile removed');
        doExplosion();
    }

    public function doExplosion():void
    {
         //This would do something different than regular letter tile.
    }
}

Hopefully this makes sense, I needed to add as much info as I could without creating a TL;DR

ArgumentError: Error #2108: Scene not found

I'm working on a 2D animation project with some interaction.

ArgumentError: Error #2108: Scene 04 - Interaction : Doughnut was not found. - this is the type of error i'll get at almost every button involving it to go to another scene.

all scenes existed and all scenes are named correctly. but the error will always come up.

this is basically one of the codes (on a seperate as layer) :

  stop();

  Fererro.addEventListener(MouseEvent.CLICK, expand4) 

  function expand4(event:MouseEvent):void 
 {gotoAndPlay(1, "05 - Interaction : Forerro");}

I've tried running the whole movie, only the scenes, published it but nothing is working. I've tried changing the scene titles into shorter ones but that does not help either.

unable to add textinput at the end of the text in flex 3

I am trying to add text input at the end of the text input, I tried to get the x and y position of the last word(or letter) of the text, but in vain. I cant use textfield in flex. Do anyone have any suggestion.

Below is the code MemoStepLabelBox.as

package {
import mx.controls.Label;
import mx.controls.Spacer;
import mx.controls.Text;
import mx.controls.TextInput;
import mx.core.Container;

public class MemoStepLabelBox extends Container
{
    public function MemoStepLabelBox()
    {
        super();
    }

    public var textLabel:Text;

    public var spacer:Spacer;

    public var input:TextInput;



    override protected function createChildren():void
    {
        super.createChildren();
        addChild(textLabel);
        if (spacer)
        {
            addChild(spacer);
        }
        if (input)
        {
            addChild(input);

        }

    }

    override protected function measure():void
    {
        super.measure();

        measuredMinWidth = 0;
        measuredWidth = 0;

        measuredMinHeight = textLabel.measuredMinHeight;
        measuredHeight = textLabel.measuredHeight;

        if (spacer)
        {
            measuredMinWidth += spacer.measuredMinWidth;
            measuredWidth += spacer.measuredWidth;
            measuredMinHeight = Math.max(measuredMinHeight, spacer.measuredMinHeight);
            measuredHeight = Math.max(measuredHeight, spacer.measuredHeight);
        }

        if (input)
        {

            measuredMinWidth += input.measuredMinWidth;
            measuredWidth += input.measuredWidth;
            measuredMinHeight = Math.max(measuredMinHeight, input.measuredMinHeight);
            measuredHeight = Math.max(measuredHeight, input.measuredHeight);
        }
    }

    override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
    {
        super.updateDisplayList(unscaledWidth, unscaledHeight);

        var labelWidth:Number = textLabel.getExplicitOrMeasuredWidth();
        var requiredWidth:Number = labelWidth;

        if (spacer)
        {
            spacer.setActualSize(spacer.getExplicitOrMeasuredWidth(), spacer.getExplicitOrMeasuredHeight());
            requiredWidth += spacer.width;
        }

        if (input)
        {
            input.setActualSize(input.getExplicitOrMeasuredWidth(), input.getExplicitOrMeasuredHeight());
            requiredWidth += input.width;
        }

        if (unscaledWidth)
        {
            var currentX:Number;
            if (requiredWidth > unscaledWidth)
            {
                currentX = unscaledWidth;

                if (input)
                {
                    input.move(currentX - input.width, (unscaledHeight - input.height) / 2);
                    currentX = input.x;
                }
                if (spacer)
                {
                    spacer.move(currentX - spacer.width, (unscaledHeight - spacer.height) / 2);
                    currentX = spacer.x;
                }

                textLabel.setActualSize(currentX, textLabel.getExplicitOrMeasuredHeight());
                textLabel.move(0, (unscaledHeight - textLabel.height) / 2);
            }
            else
            {
                textLabel.setActualSize(labelWidth, textLabel.getExplicitOrMeasuredHeight());
                textLabel.move(0, (unscaledHeight - textLabel.height) / 2);
                currentX = textLabel.x + textLabel.width;

                if (spacer)
                {
                    spacer.move(currentX, (unscaledHeight - spacer.height) / 2);
                    currentX = spacer.x + spacer.width;
                }
                if (input)
                {
                    input.move(currentX, (unscaledHeight - input.height) / 2);
                    currentX = input.x + input.width;
                }

            }
        }
    }
}
}

main.mxml

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://ift.tt/1aBfKeP" xmlns:local="*"  creationComplete="stack.selectedIndex = 0;">
<mx:Script>
    <![CDATA[
    import mx.controls.Alert;

    public var badWords:Array = ["shit",'abcd','shut-up','aaa'];

    /* public function onInsertStepsClick():void
     {
     var inputString:String = textArea.text;
     for each (var word:String in badWords) {
     var replStr:String = '****';

     // check if string is a naughty word
     var regex:RegExp = new RegExp('^' + word + '$', 'gism');
     inputString = inputString.replace(regex, replStr);

     // check if string starts with naughty word
     regex = new RegExp('^' + word + '(\\W)', 'gism');
     inputString = inputString.replace(regex, replStr + '$1');

     // check if string ends with naughty word
     regex = new RegExp('(\\W)' + word + '$', 'gism');
     inputString = inputString.replace(regex, '$1' + replStr);

     // check if naughty word is in string
     regex = new RegExp('(\\W)' + word + '(\\W)', 'gism');
     inputString = inputString.replace(regex, '$1' + replStr + '$2');
     }
     if(inputString.indexOf(replStr) >= 0){
     Alert.show("Please remove bad words");
     }
     }*/


    ]]>
</mx:Script>
<mx:ViewStack width="500" height="50%" id="stack">
    <!--  <mx:TextArea id="textArea" width="600" height="400" ></mx:TextArea>
      <mx:Button label="Insert Steps" width="100" click="onInsertStepsClick()"/>-->

    <local:MemoStepLabelBox id="hbxHasInput" width="100%">
        <local:textLabel>
            <mx:Text id="txtStep" width="100%"
                     text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaa"
                     styleName="f1"
                    />
        </local:textLabel>
        <local:spacer>
            <mx:Spacer id="hasInputSpacer" width="6" themeColor="green" />
        </local:spacer>
        <local:input>
            <mx:TextInput id="txtIn" width="100" paddingTop="0"
                          paddingBottom="0"
                    />
        </local:input>

    </local:MemoStepLabelBox>

</mx:ViewStack>
</mx:Application>

Server not picking up information from database and passing it to client

I am trying to get my server to get the sso from the logged in user (web) and pass that to an AS3 client.

If I set a specific SSO in the client (bellow) the server picks up the user from the database.

Currently I get the error: ER 1: You have an invalid SSO ticket. Please re-login and then reload.

package 
{
    import com.archicruise.external.RoomManager;
    import com.archicruise.server.Connection;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.LoaderInfo;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.system.Security;
    import flash.system.System;

    public class Main extends Sprite 
    {
        [Embed(source = '../assets/client_back.png')] private static const clientBackImage:Class;

        public static var SITE_URL:String = "http://localhost/archicruise/";

        public var roomLoader:RoomManager;
        private var connection:Connection;

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

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

            //Add client background
            addChild(new clientBackImage() as Bitmap);

            //Got an SSO ticket?
            var ssoTicket:String = LoaderInfo(this.root.loaderInfo).parameters["sso"];
            if (ssoTicket == "" || ssoTicket == null) ssoTicket = "2e44550b0d6e98cc9f26c39e53213e24";

            //Initialize the connection
            Security.allowDomain("*");
            connection = new Connection("localhost", 9339, this, ssoTicket);;
        }

    }

}

I am getting the ssoTicket value after a user logs into a website and launches the page with the SWF like so:

var flashvars = {
    sso: "<?php echo $self['sso_ticket']; ?>"
};

The Handler from the server:

public static void login(string ssoTicket, TcpClient client)
{
    if (ssoTicket == "")
    {
        client.Disconnect();
        return;
    }
    Log.Info("Client " + client.index + " logging in with SSO: " + ssoTicket);

    if (DBManager.database.getString("SELECT COUNT(*) FROM `users` WHERE `sso_ticket` = '" + ssoTicket + "'") != "0")
    {
        DBManager.database.closeClient();
        //build the user object
        UserObject userObject = newObject(ssoTicket, client);

        foreach (UserObject user in clientObjects)
        {
            if (user.username == userObject.username)
            {
                user.tcpClient.Disconnect();
            }
        }

        if (clientObjects.Count <= client.index || clientObjects[client.index] == null)
        {
            client.userObject = userObject;
            clientObjects.Add(userObject);
        }
        else
        {
            client.userObject = userObject;
            clientObjects[client.index] = userObject;
        }
        client.sendData("LO" + (char)13 + userObject.ToPrivate());
        DBManager.database.closeClient();
    }
    else
    {
        DBManager.database.closeClient();
        client.sendData("ER 1: You have an invalid SSO ticket. Please re-login and then reload.");
    }
}

Need help on AS3 package design

The below code is not working for me. Can you guys look into it. I want to load external swf to my main file.

package {
import asFiles.BGloader;
import flash.net.*;
import flash.events.*;
import flash.display.*;
import flash.text.TextField;

public class Main extends MovieClip {
    private var tField:TextField
    private var json;
    public var parsedJSONData: Object;
    public var numberOfBooks: int;
    public var modesTypesX: Array = ["680", "860", "1040", "780", "980"];

    public function readJSON() {
        parseJSON();
        myTest()
    }
    private function parseJSON(): void {

        var BGscreen = new URLLoader();
        BGscreen.load(new URLRequest("interface/BGscreen.swf"));
        addChild(BGscreen);

        trace("read this");
        trace("SWF file loaded successfully!");
        trace("Parsing SWF...");
        trace("RESULTS:");
    }

//below one working fine in another file

private function myTest(): void {
        tField = new TextField();
        tField.text = "testing";
        addChild(tField);
    }
}

}

// need to understand why its not working... please help.

Thank you

Embedding resource using script

I have to create library/support application file with 1000s of sound files (total size around 1GB). For that I am planning to use following code:

package Resources.questions
{
    public class HindiVoice
    {
        [Embed(source="1.mp3",symbol="c1")]
        private static const c1:Class;
        [Embed(source="2.mp3",symbol="c2")]
        private static const c2:Class;
        //To-Do add 1000 files with symbol definition
        public function HindiVoice()
        {

        }
    }
}

Above file is hard to maintain. Can I use "for loop" to iterate from 1 to 1000 and embed sound files in the project? I am using flash developer 4.7.

AS3 Check if variable is String outputs MouseEvent info

I am trying to check if a variable is a string, in this case if it has a url in the string. But the code is executing and in the trace statement I get this:

if (theWebsite is String)
trace(theWebsite);

output: [MouseEvent type="click" bubbles=true cancelable=false eventPhase=3 localX=2259.8671875 localY=2485.85205078125 stageX=1003.25 stageY=71 relatedObject=null ctrlKey=false altKey=false shiftKey=false buttonDown=false delta=0 commandKey=false controlKey=false clickCount=0] MainStage? [object Main_Activate] and website? [MouseEvent type="click" bubbles=true cancelable=false eventPhase=3 localX=2259.8671875 localY=2485.85205078125 stageX=1003.25 stageY=71 relatedObject=null ctrlKey=false altKey=false shiftKey=false buttonDown=false delta=0 commandKey=false controlKey=false clickCount=0]

Here is the code that creates this variable.

1.

MenuScreen.One_btn.addEventListener(MouseEvent.CLICK, webViewButton("http://ift.tt/tv1JJF"));

2.

public function webViewButton(theWebsite:String):Function  {
            trace("made it here: " + theWebsite);
            return function(e:MouseEvent):void {
                trace("made it here too: " + theWebsite);
            removeMenuScreen(theWebsite);
            }
        }

3.

public function removeMenuScreen(theWebsite:String = null, e: Event = null) {

            if (theWebsite is String) {
                trace("But did I make it here? " + theWebsite);
                // OUTPUTS all the above code mentioned earlier. 
            }

I am using that function for other things as well so that is why its set up that way. HOW can I fix this to have that code execute only if it is a defined string? Thanks for any tips.

mardi 26 janvier 2016

Rollover image (on server) in loader, each 10 seconds AS3

I'd like to put a loader on my AIR app and display images that I have on a server. I'd like to create a RollOver each 10 seconds.

Can I do it without putting in the AS3 code the name of the image file ? (as it's possible I'll add some images in the future on the server side).

Exemple :

pubContent2.load(new URLRequest("http://ift.tt/1WNkY1k"));

and maybe create a timer that calls the next image after 10 seconds..? What do you think ?


EDIT

If I know that there won't be more that 4 images. Maybe I can do an Array like that :

var images:Array = [{source:"http://ift.tt/1nOshKf"}, {source:"http://ift.tt/1nOsg8V"}, {source:"http://ift.tt/1WNkYhA"}, {source:"http://ift.tt/1nOshKh"}];  

Do you think it's a good idea ? (And if I have only 3 images at the beginning, will it cause a bug in the code ?)

AS3 Feather Edge Circle with gradient

I'm trying to draw a very big circle and feather the edge with a gradient

        var mat:Matrix= new Matrix();
        var colors:Array=[0x000000,0x000000];
        var alphas:Array=[1,0];
        var ratios:Array=[200,255];

        var size:int = (circleMenu.innerRadius + circleMenuOffset) * circleMenuScale;

        mat.createGradientBox(size * 2,size * 2, 0 ,  0 ,  0);
        circleMenuBackground.graphics.clear();
        circleMenuBackground.graphics.beginGradientFill(GradientType.RADIAL, colors,alphas,ratios,mat);
        circleMenuBackground.graphics.drawCircle(size/2,size/2,size);
        circleMenuBackground.graphics.endFill();

The circle is very big, and I want the gradient to start at the last 10% or so of the circle. I can either make it fully black, or disappear, I can't work out how to get a very small gradient. Any clues gratefully appriciated!

How do I change this unwanted loader size scaling in as3?

Hello and thank you for your time.

I am using a loader object to display an image on the stage in AS3. The problem is that the loader is being resized or scaled somehow to a size that does not match the image that is being loaded. This is causing the image to not show up on the stage, and I am not sure what I am doing wrong.

Here is how I load the image:

        normalBanner = new Loader();
        normalBanner.contentLoaderInfo.addEventListener(Event.COMPLETE, function (e:Event): void{
                                                        addChild(normalBanner);
                                                        normalBanner.x = -1920;
                                                        normalTL = new TimelineLite();
                                                        normalTL.append(new TweenLite(normalBanner, .001, {x:0}));
                                                        normalTL.append(new TweenLite(normalBanner, .5, {alpha:1}));
                                                        normalTL.pause();
                                                        trace("normalBanner bounds: " + getBounds(normalBanner));
                                                        fadeNormalTL = new TimelineLite();
                                                        fadeNormalTL.append(new TweenLite(normalBanner, .001, {x:0}));
                                                        fadeNormalTL.append(new TweenLite(normalBanner, .5, {alpha : 0}));
                                                        fadeNormalTL.append(new TweenLite(normalBanner, .001, {x:-1920}));
                                                        fadeNormalTL.pause();
                                                        });
        normalBanner.load(new URLRequest(config.xmlData.setUp.banners.normalBanner));

The trace("normalBanner bounds: " + getBounds(normalBanner)); outputs normalBanner bounds: (x=-1920, y=0, w=3840, h=1080)

If anyone could shed some light on what might be causing the problem, it would be a huge help, thanks.

Is there a simple way to receive statistics for my AIR app (as which frame is the most readed)?

I've got an AIR app with 5 frames and some AS3 code on each frame :

My scenario

Is there a simple way to put a statistic analytic of the app that send me stats like which frame is the most visited ?

Making a camera follow the gameobject (AS3,Unity,XNA) platform independent

i am using Unity with a custom framework, it works like AS3 and XNA ,

let's assume i am using something like XNA and AS3,

I created a Camera class and i want it to follow the player, right now the camera is shakking and the movement of the player is not smooth. i think it's on the direction part of the code, the movement of the camera shakes(without triggering the shake function). if someone finds the bug in the code please let me know.

    override public void update()
    {
        base.update();

        if (getState() == STATE_STALE)
        {
        }
        else if (getState() == STATE_RETURNING_TO_START)
        {
            //CUtils.log ("x camara: " + getX ());
            if (getX() <= 0)
            {
                setState(STATE_STALE);
                return;
            }
        }
        else if (getState() == STATE_FOLLOW_PLAYER)
        {
            lookAt(mPlayerToFollow.getX(), mPlayerToFollow.getY());

            Vector3 dir = new Vector3(CGame.inst().getPlayer().getX() - mObjectToFollow.getX(), CGame.inst().getPlayer().getY() - mObjectToFollow.getY(), 0);
            Vector3.Normalize(dir);
            Vector3.Dot(dir, new Vector3(SPEED_RETURNING_TO_PLAYER, SPEED_RETURNING_TO_PLAYER, 0));

            dir.x = dir.x * (SPEED_RETURNING_TO_PLAYER);
            dir.y = dir.y * (SPEED_RETURNING_TO_PLAYER);


            mObjectToFollow.setVelXY(dir.x, dir.y);
            //  
            mObjectToFollow.update();

            lookAt(mObjectToFollow.getX(), mObjectToFollow.getY());
        }

        //  
        //  
        if (CMath.dist(mObjectToFollow.getX(), mObjectToFollow.getY(), CGame.inst().getPlayer().getX(), CGame.inst().getPlayer().getY()) < SPEED_RETURNING_TO_PLAYER)
            {
            setState(STATE_FOLLOW_PLAYER);
            }
        //}

        // Shake update.
        if (mShakeTime > 0.0)
        {
            mShakeTime -= 1.0f / 60f;
            shake();
            checkLimits();
        }
        else 
        {
            stopShaking();
        }

        checkLimits();

        Camera.main.transform.position = new Vector3 (getX() + getWidth() / 2, (getY() + getHeight() / 2) * -1, -10.0f);
    }

Adobe AIR working date-picker ANE for Android and iOS

Does anyone know any good date-picker Adobe AIR extension (including paid ANEs) for showing up the native date-picker from iOS and Android to let the user input his date of birth? I only need the date-picker feature, so paying 100$ just for this is not a good idea (e.g. FPNativeUI). It can also be one ANE for Android, one for iOS.

Freshplanet DatePicker - I set it up, tried the .apk on Android and nothing shows up with this code (and ANE's implementation):

        // Required params
        var currentDate : Date = new Date();
        var callback : Function = function( selectedDate:String ) : void {
            trace("selected date = ", selectedDate.toString());
        }

        // Native extension call
        AirDatePicker.getInstance().displayDatePicker(currentDate, callback);

Mateuszmackowiak NativeDialogs works on Android, but when I tested it on iOS, it wasn't working

I also checked Milkman's ANE, with no luck.

AS3 check if class name is

I want to know if a Class is the main stage, in other words...

if it is "ThisName" then...

My code is:

MainStage = this.parent as MovieClip;
trace("scroll Stage: " + MainStage); // output: scroll Stage: [object Main_Activate]

but how would I write it this way?

if(MainStage == [object Main_Activate])
then run my code.

In this last example [object Main_Activate] is getting errors.

Unable to get ssoTicket from database unless specifically set in Flash

I have been working on getting a game I created working with a friend about 8 years ago, as it never did work.

I have got everything to work and can run locally, with the exception of sso validation.

I need to get the users ssoTicket from MySQL database, which works but I am having to set a specific value to allow connection to a user.

I am looking for some advice on what to be searching for to resolve this, as this is a learning curve.

package 
{
    import com.archicruise.external.RoomManager;
    import com.archicruise.server.Connection;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.LoaderInfo;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.system.Security;
    import flash.system.System;

    public class Main extends Sprite 
    {
        [Embed(source = '../assets/client_back.png')] private static const clientBackImage:Class;

        public static var SITE_URL:String = "http://localhost/archicruise/";

        public var roomLoader:RoomManager;
        private var connection:Connection;

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

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

            //Add client background
            addChild(new clientBackImage() as Bitmap);

            //Got an SSO ticket?
            var ssoTicket:String = LoaderInfo(this.root.loaderInfo).parameters["sso"];
            if (ssoTicket == "" || ssoTicket == null) ssoTicket = "2e44550b0d6e98cc9f26c39e53213e24";

            //Initialize the connection
            Security.allowDomain("*");
            connection = new Connection("localhost", 9339, this, ssoTicket);;
        }

    }

}

I am getting the ssoTicket value after a user logs into a website and launches the page with the SWF like so:

var flashvars = {
    sso: "<?php echo $self['sso_ticket']; ?>"
};

Error on comparing Shared Object Data with a Number

Hey everyone so been at this for a couple hours now and cant seem to figure it out.

So I have a Shared Object Data variable sharedObjectStarsPoints that is used to keep track of the number of stars that a player unlocks in a game.

So what I am trying to accomplish is say the player has unlocked 2 stars and retrys the level again but this time the player gets only 1 star I want the shared Object to ignore the player only getting the 1 star and keep the highest number of stars in the data base in this example that number would be 2. Player can get total of 3 stars.

So when the player loses it takes them to the game over screen which is where I remove all the ENTER FRAME listeners and everything else. This is also where I setup how many stars the player unlocked and try to use the logic from above to compare the two numbers like so:

so in the same function this is when the variable starsCollected is incremented.

            if (bJanObjecMult)
            {
                objectiveScreen.janStars.bonus.gotoAndPlay(2);
                //add 1 to star collector number
                starsCollected += 1;
                //Add one to levels screen stars completed
                updateStarsCollected();
            }else
            {
                objectiveScreen.janStars.bonus.gotoAndStop(1);
            }
            if (bJanObjectPoints)
            {
                objectiveScreen.janStars.points.gotoAndPlay(2);
                //add 1 to star collector number
                starsCollected += 1;
                //Add one to levels screen stars completed
                updateStarsCollected();
            }

then below these if statements are where I try to use the logic like so:

if (sharedObjectStarsPoints.data.janStars > starsCollected)
        {
            trace("DONT SAVE DATA");
        }else
        {
            sharedObjectStarsPoints.data.janStars = starsCollected; 
            allSharedObjectStarsData();
            sharedObjectStarsPoints.flush();
            trace("SAVE DATA");
        }

so as you can see I am basically saying if my shared object data is greater than the stars collected data, then dont save anything because say the shared data has 2 and the other data only has 1 then I dont want anything to be replaced. But if that is not the case and its less than the starsCollected data then save the new information and update it.

Also to note whenever the player restars the game the starsCollected number var is set back to 0;

please any help would be appreciated!

lundi 25 janvier 2016

Search inside a DataGrid

I have been fighting with some code I wrote in the past and trying to tweak it. Currently my search only searches for a matching first character of a word. I need to search more in depth. For instance if I search for planet in this string:

"Earth is a planet"

I get nothing but if I search for planet in this next string:

"Planet earth is amazing"

I get the data grid to show just that line.

I want to be able to search for a word the shows the line regardless of whether its in the beginning of a string or end of one.

Can someone help me out? Thanks in advance.

import fl.controls.DataGrid;
import fl.controls.TextInput;
import fl.controls.dataGridClasses.DataGridColumn;
import fl.data.DataProvider;

var voddb:DataProvider = new DataProvider();
voddb.addItem({title:"Earth is a planet", detail:"ALE 0110"});
voddb.addItem({title:"Planet Earth", detail:"ALE 0210"});
 voddb.addItem({title:"Jupiter is a planet", detail:"ALE 0310"});
 voddb.addItem({title:"Aplanet Jupiter", detail:"ALE 0410"});
 voddb.addItem({title:"Another amazing planet is mars", detail:"ALE 0510"});
 voddb.addItem({title:"Planets include earth and mars:", detail: "ALE      0610"});

 vodTextInput.addEventListener(Event.CHANGE, changeHandler);

 var titleCol:DataGridColumn = new DataGridColumn("title");
 titleCol.headerText = "Title";

 var detailCol:DataGridColumn = new DataGridColumn("detail");
 detailCol.headerText = "Details";
 detailCol.sortOptions = Array.DESCENDING;

 vodDataGrid.addColumn(titleCol);
 vodDataGrid.addColumn(detailCol);
 vodDataGrid.dataProvider = voddb;

 function changeHandler(event:Event):void {
    var arr:Array = voddb.toArray();
    var filteredArr:Array = arr.filter(filterDataProvider);
    vodDataGrid.dataProvider = new DataProvider(filteredArr);
}
 function filterDataProvider(obj:Object, idx:String, arr:Array):Boolean {
    var txt1:String = vodTextInput.text;
    var txt2:String = obj.title.substr(0, txt1.length);
    if (txt1.toLowerCase() == txt2.toLowerCase()) {
    return true;
    }
    return false;
}

open file location with as3

I have a <s:List /> that contain a bunch of files. On right click I open a menu at the (x, y) position of the mouse that lets the user "Open File Location". My struggle is opening the file location and selecting (without opening) the file much like Window's explorer. The closest I have come in opening the parent folder and using file.openWithDefaultApplication();, which opens the folder that the file is in without showing the user the actual file.

AS3 socket cannot load data from

I have searched internet for a lot of times but could not find any clue. I am using sockets to connect to socket server. (Also we tryed different socket policy files, but none worked)

    private var SERVER_URL : String = "http://192.168.0.105";
    private var PORT_NUMBER : int = 1435;

    private var _socket : Socket;

    // signal
    private var _signal : Signal;

    public function BackendService()
    {
        // nastavenie socketu
        _socket = new Socket();
        _socket.addEventListener(Event.CONNECT, connectHandler);
        _socket.addEventListener(Event.CLOSE, closeHandler);
        _socket.addEventListener(ErrorEvent.ERROR, errorHandler);
        _socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        _socket.addEventListener(ProgressEvent.SOCKET_DATA, HandleMsgFromServer); // ak pride sprava zo serveru

        Security.allowDomain("*");
        Security.allowInsecureDomain("*");
        Security.loadPolicyFile("http://ift.tt/1nJOKIl"); 

        // signal na dispatchovanie eventov
        _signal = new Signal();

        connect(); // I am doing it from other class, but for sake of example, I am calling from here
    }

    public function connect():void
    {
        _socket.connect(SERVER_URL, PORT_NUMBER);
    }

My crossdomain - socket policy file are sitting on port 8000 and looks like this:

<cross-domain-policy>
<site-control permitted-cross-domain-policies="master-only"/>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>

I am getting this error: Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: file:///C:/projects/TennisHeroes/bin/TennisHeroes.swf cannot load data from http://ift.tt/1OSbmgz.

Thank you very much for any advice!

Actionscript 3 Convert a MovieClip to Video file

I have a movieclip that include video and animated movieclip object which user load the image inside it. I need to convert the movieclip as video file at runtime. Because I want to open final video on mobile device also.

My first aim is convert the movieclip as a video file. Is there any way to convert it or an alternative way to open swf on mobile devices?

I searched on the internet but I can not find any solution about that.

How to get Change x and y coordinate of an object if we change the screen resolution in as3

If i change the screen resolution then how i will get Change x and y position of an object:

For example my object current x position is 500 and y position is 100 and my current screen resolution is 1360*768

Now i change the screen resolution to 800*600

Then how i will get the changed x and y position of my object.

I am using the following formula to find the changed/updated x and y position:

x = (500 * 800) / 1360; y = (100 * 600) / 768;

But it is not giving Correct result to me, So please Help me to solve this problem.

dimanche 24 janvier 2016

JSON.decode issue

I found an old MMO game I had been working on with a friend some years ago, but when running the bellow code (from a bigger file) it just keeps throwing:

RoomManager.as(43): col: 14 Error: Access of undefined property JSON.

public function RoomManager(_con:Connection, _rmap:String = null, _rwarps:String = null)
    {
        _connection = _con;
        roomMap = JSON.decode (_rmap) as Array;
        if(_rwarps != null && _rwarps != "") roomWarps = JSON.decode (_rwarps) as Array;
        ObjectManager.connection = _con;
    }

I have been unable to find anything to give me some detail to further explore the issue, can anyone advise what to look at?

Thanks

as 3 : problems with putting audio in a quiz

I have a quiz with radiobuttons that works. But now i want to have audio for each radiobutton. I searched and googled and tried so much but nothing seems to work.

QuizApp.as
    public class QuizApp extends MovieClip {
    //for managing questions:
    public var quizQuestions:Array;

    public var currentQuestion:QuizQuestion;
    public var currentIndex:int = 0;
    //the buttons:
    public var prevButton:Button;
    public var nextButton:Button;
    public var finishButton:Button;
    //scoring and messages:
    private var score:int = 0;
    private var status:TextField;

    public var asoundArray:Array;
    public var asoundIndex:int = 0;
    public var currentasound:asoundArray;

    public function QuizApp() {
        quizQuestions = new Array();
        asoundarray = new Array();
        createasounds();
        createQuestions();
        createButtons();
        createStatusBox();
        addAllQuestions();
        hideAllQuestions();
        firstQuestion();
    }

    public function createasounds () {
        asoundArray.push("sound1", 
                        "sound5",
                        "sound9",
                        "sound13");
    }

asoundArray will be controlled by the playabtn. But now everytime i get the error: 1046: Type was not found or was not a compile-time constant:asoundArray.

I checked and tried many options. I have nothing with the same name. I only have the playabtn on the stage. No library items with any similar names and checked the spelling a few times.

If anyone can help me or point me in the right direction...that would be really great.

I am a beginner in flash and try to make tests for the students. Did many times before, but the way i am doing now :) yes doesn`t seem to go the way i want. But that way you seem to learn a lot more then you ask for.

But seriously ..please help.

How do I removeChild after I addChildAt in my stage?

I've 2 movieclips and 1 button that I add using addChildAt after player solve the puzzle. The button is for the player to go to the next level which is the next scene, but after I click it, on the next scene the button is still there and so are the movieclips.

How do I remove them? Some things I tried.

if (level_2.parent){
      level_2.parent.removeChild(level_2)
     }

But, if I did this,

if (level_2.parent){
level_2.parent.removeChild(level_2)
level_2 = null
}

it remove the button, but theres an error said " Parameter child must be non-null." and it refer to the code that I write about calling the button by

addChildAt(level_2,6);

samedi 23 janvier 2016

call event function in another event function As3

i am calling function on another function like below.

function loadXML(e:Event = null):void{

    xmlData = new XML(e.target.data);
    //var production:String = xmlData.production.app_id.text();
    trace(xmlData);
    var states:String = xmlData.state.place.text();
    var desc:String = xmlData.state.description.text();
    var image:String = xmlData.state.image.text();
    trace('this is working');   
}
obj.addEventListener(MouseEvent.MOUSE_OVER,fl_MouseOverHandler);
function fl_MouseOverHandler(event:MouseEvent):void
{
    loadXML();
}

in thi s case warning occured Cannot access a property or method of a null object reference how do i resolve this?

Away3d - Error #3691: Resource limit for this resource type exceeded

I'm stuck on an error that I can't make go away.

I'm using Away3d with a skybox as a panorama player, after changing the skybox texture a few times I sometimes get this error. I'm not sure if it's only happening in debug player only.

I assume something is not being cleared out but I can't work out what.

I could change the skybox to a simple geometry and see if that's better, then I can absolutely make sure the textures are disposed.

Anyone any clues?

Error: Error #3691: Resource limit for this resource type exceeded.
    at flash.display3D::Context3D/createCubeTexture()
    at away3d.textures::CubeTextureBase/createTexture()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\textures\CubeTextureBase.as:25]
    at away3d.textures::TextureProxyBase/getTextureForStage3D()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\textures\TextureProxyBase.as:65]
    at away3d.materials.passes::SkyBoxPass/activate()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\materials\passes\SkyBoxPass.as:110]
    at away3d.materials::MaterialBase/activatePass()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\materials\MaterialBase.as:408]
    at away3d.core.render::DefaultRenderer/drawSkyBox()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\render\DefaultRenderer.as:140]
    at away3d.core.render::DefaultRenderer/draw()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\render\DefaultRenderer.as:111]
    at away3d.core.render::RendererBase/executeRender()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\render\RendererBase.as:281]
    at away3d.core.render::DefaultRenderer/executeRender()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\render\DefaultRenderer.as:70]
    at away3d.core.render::RendererBase/render()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\core\render\RendererBase.as:245]
    at away3d.containers::View3D/render()[C:\workspace\flash\libs\lib_pano_away3d\src\away3d\containers\View3D.as:698]
    at co.beek.pano::Pano/onEnterFrame()[C:\workspace\flash\libs\lib_pano_away3d\src\co\beek\pano\Pano.as:1516]

MouseEvent.MOUSE_UP not working for AS3 code

I am trying to use the drag feature of flash to move a sprite I created. I understand that I can add the mouse up event inside of the mouse down event and add to the stage but I would prefer to see if I can get this working first. Part of the reason I want to use sprite instance mouse up handler is later in code I am referencing the event.target.name for further processing. Below is the code that is giving me the issue with mouse up.

var cnt_fat_1:Sprite = new Sprite();
var g : Graphics = cnt_fat_1.graphics;
g.lineStyle(0,0x555555,0.5);
g.beginFill(0xFFffff);
g.drawRect( 0, 0, 25, 25 );
g.endFill( );
cnt_fat_1.x = 20
cnt_fat_1.y = 20

cnt_fat_1.addEventListener(MouseEvent.MOUSE_DOWN, move_choose)
cnt_fat_1.addEventListener(MouseEvent.MOUSE_UP, move_stop)

addChild(cnt_fat_1)

function move_choose(event:MouseEvent):void {
event.target.startDrag(true);   
 }

function move_stop(event:MouseEvent):void {
event.target.stopDrag() 
}

TextEvent won't work on IOS with AS3, any idea why ?

I'v got this code. It works fine on Android. When the user type his phone number, the TextInput has a special format.

Here's my code :

displayPhonetxt.phoneTxt.restrict = "0-9";
    displayPhonetxt.phoneTxt.maxChars = 8;
    displayPhonetxt.phoneTxt.addEventListener(TextEvent.TEXT_INPUT, onPhoneInput);

function onPhoneInput(evt: TextEvent): void {
    if (displayPhonetxt.phoneTxt.length == 2 || displayPhonetxt.phoneTxt.length == 5) {
        displayPhonetxt.phoneTxt.appendText(".");
        var leng: int = displayPhonetxt.phoneTxt.text.length;
        displayPhonetxt.phoneTxt.setSelection(leng, leng);
    }
}

But on IOS, the function onPhoneInput doesn't work. I can enter 8 characters, but there not seperate by a dot (.) if displayPhonetxt.phoneTxt.length == 2 or displayPhonetxt.phoneTxt.length == 5.

Any idea why ?

How to edit application descriptor in Flash Builder 4.7

I am trying to migrate my AIR mobile project from FlashDevelop to Adobe Flash Builder 4.7. In FlashDevelop I have my AIR application descriptor application.xml. When I created a new Flash Builder project it generated a new application descriptor (Mail-app.xml) in the /src folder, and put it into /bin-debug. However, when I try and copy the configuration from my old application descriptor to the new one, the Main-app.xml in the /bin-debug folder remains the same. I tried cleaning project, but it immediately recreates some sort of default application descriptor in /bin-debug. Where and what should I change so the changes will be picked by Flash Builder?

OnEdit need to send emails from a column

When in column O cell is mentioned "Shipped" I want to send emails in column C (with corresponding row)

Need support to get this script right

function sendEmail(e) { var thisSheet = e.source.getActiveSheet(); if (thisSheet.getName() !== 'CRM' || e.range.columnStart !== 15 || e.range.rowStart == 1 || e.value !== 'Shipped') return; var body, headers = thisSheet.getRange(1, 1, 1, 6) .getValues()[0], thisRow = thisSheet.getRange(e.range.rowStart, 1, 1, 6) .getValues()[0], recipientsEMail = (thisSheet.getRange.columnStart !==3 || e.range.rowStart ==1) .getValues()[0], recipients = recipientsEMail, subject = "Your Vehicle is shipped " + e.source.getName(), body = "", i = 0; while (i < 6) { body += headers[i] +' - ' + thisRow[i] +'\n'; i++; }

MailApp.sendEmail(recipients, subject, body);

}

My sheet

vendredi 22 janvier 2016

Can't upload CameraRoll from IOS but I can upload CameraUI

I've got this code in AS3 for AIR app. I had to re-write it for IOS as the cameraUI wasn't working on it (only on Android).

So now, when I want to upload a picture from the camera, it's working. But if I choose a picture from Camera Roll, my feedback text returns : "Asynchronous media promise." and stay stuck on it...

Any idea what I did wrong on this code ? Here's what I did :

function initCameraRoll(evt: Event): void {
    if (CameraRoll.supportsBrowseForImage) {
        cameraRoll.addEventListener(MediaEvent.SELECT, imageSelected);
        cameraRoll.addEventListener(Event.CANCEL, browseCanceled);
        cameraRoll.addEventListener(ErrorEvent.ERROR, mediaError);
        cameraRoll.browseForImage();
    } else {
        trace("Image browsing is not supported on this device.");
    }

}
function initCamera(evt: Event): void {
    if (CameraUI.isSupported) {
        feedbackText.text = "Initializing...";
    cameraUI.addEventListener(MediaEvent.COMPLETE, imageSelected);
    cameraUI.addEventListener(Event.CANCEL, browseCanceled);
    cameraUI.addEventListener(ErrorEvent.ERROR, mediaError);
    cameraUI.launch(MediaType.IMAGE);
    } else {
        trace("CameraUI is not supported.");
    }
}


function browseCanceled(event: Event): void {
    feedbackText.text = "Browse CameraRoll Cancelled";
}



function mediaError(event: Event): void {
    feedbackText.text = "There was an error";
}

var dataSource: IDataInput;



function imageSelected(event: MediaEvent): void {
    feedbackText.text = "Image selected";
    var picture:File = event.data.file;
    cameraUI.removeEventListener(MediaEvent.COMPLETE, imageSelected);
    cameraUI.removeEventListener(Event.CANCEL, imageSelected);
    cameraUI.removeEventListener(ErrorEvent.ERROR, mediaError);

    var mediaPromise:MediaPromise = event.data;

    this.mpLoader = new Loader();
    this.mpLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMediaPromiseLoaded);
    this.mpLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorMedia);
    this.mpLoader.loadFilePromise(mediaPromise);



 function onMediaPromiseLoaded(e:Event):void{

        if (allPuzzles.photo.photo1saved && allPuzzles.photo.photo2saved) {
        feedbackText.text = "already 2 photos";
        tooMuchImg.visible = true;
        tooMuchImg.closeAverPhoto.addEventListener(MouseEvent.CLICK, hideAverImg);
    } else if(allPuzzles.photo.photo1saved){
        var mpLoaderInfo2:LoaderInfo = e.target as LoaderInfo;
     feedbackText.text = "onMediaPromiseLoaded";
    mpLoaderInfo2.removeEventListener(Event.COMPLETE, onMediaPromiseLoaded);
    mpLoaderInfo2.loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorMedia);
    Imgloader2.source = mpLoaderInfo2.loader;
    }
    else{
    var mpLoaderInfo:LoaderInfo = e.target as LoaderInfo;
    mpLoaderInfo.removeEventListener(Event.COMPLETE, onMediaPromiseLoaded);
    mpLoaderInfo.loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorMedia);
    Imgloader.source = mpLoaderInfo.loader;
    }



    dataSource = mediaPromise.open();

    if( mediaPromise.isAsync ){
       feedbackText.text = "Asynchronous media promise." ;
        var eventSource:IEventDispatcher = dataSource as IEventDispatcher;            
        eventSource.addEventListener( Event.COMPLETE, onMediaLoaded );         
    }else{
        feedbackText.text  "Synchronous media promise.";
        readMediaData();
    }
}

IOS - Loading assets from an external stripped SWF

I have a flash (AIR) application for IOS.

I package the app using adt (Air Developer Tool), while passing a list of SWFs that I intend to load externally later to be stripped of code, for the sake of argument let's say there's only one SWF I need to strip of code.

The app is packaged successfully, and a SWF that is stripped from code is created into the folder "externalStrippedSwfs".

I run the app on IOS and load from my server at runtime the stripped SWF that was created by adt. That stripped SWF contains assets (e.g. textures) that were embedded using embed tags in ActionScript 3.

When the SWF's loading is complete, no definitions exist in the application domain for some reason.

I'd like to point out that when I test this on PC everything works as it should (of course loading a SWF that is not stripped of code in that case).

Here're two different loading approaches I tried for loading the external stripped SWF, both load the SWF successfully, but both result in an empty vector of definition names on IOS.

http://ift.tt/1REn7Nb http://ift.tt/1KvFlsI

Naturally, when I try to get an asset an error is returned because no definitions exist:

try
{
    trace(ApplicationDomain.currentDomain.getDefinition("something"));
}
catch (error:Error)
{
    trace("Error: " + error.name + ", " + error.errorID + ", " + error.message);
}