lundi 31 octobre 2016

Strategy for finding a missing mouse event in AS3

Will make this brief, I have a game map with units on it and had finalized a fully interactive minimap where the units on the minimap have event listeners for rollover/rollout (displays a small popup unit data summary) and click (selects the "real" unit on the main game map and scrolls the viewpoint to that location). All done, tested, working.

I then implement an interactive scrollable unit list with more status summary data and dozens of objects with rollover/rollout/click listeners. All tested and working fine.

Then I go back and look at my minimap, and the listeners on the mini-ships aren't working anymore. Things tried:

  1. Debug code to make sure listeners still being added
  2. Debug to watch the one place where I remove those listeners to make sure that ain't happening unexpectedly
  3. Debug to watch all the places I refresh that dialog to make sure every iteration adds the listeners back
  4. Can't see that there is any transparent object on top intercepting
  5. Checked mini-ship parents to make sure I didn't turn off mouseChildren or something like that somewhere
  6. No added stage-level listener, in fact I killed all of them temporarily to test this

What happens when I debug with a breakpoint on the mini-ship listener handler is nada. It's no longer receiving mouse events. So either something I haven't thought of has stopped them from listening or something I don't know of is intercepting.

So what is the strategy here? How can I find the break in the chain?

Retrieving datas within an Array

This is probably easy but I just cannot get the answer. Here is a simple Array:

I want the information to be distributed from an Input textBox to different dynamic textBox after a click. I am OK with buttons.

var ERLQ1:Array = ["ERLQ1",  "N09°02.61 / E100°49.11", "ErawanLq"];
InputText = "ERLQ1";
    //I want to display:
Txt1 = "ERLQ1"           //Being first part of the array as main reference.
Txt2 = "N09°02.61 / E100°49.11"   // Should be:   String(ERLQ1[1])
Txt3 = "ErawanLq"                 // Should be:   String(ERLQ1[2]) 

First time I write in a forum like this. Please forgive if not perfect. Thanks in advance. Andre

Foreground for Flash games

I've noticed that most Flash games (and other SWFs) have foregrounds incorporated into them. The reason being to cover up graphic you're not supposed to see upon entering full screen (graphic outside the boundaries of the stage).

The foreground is simply a piece of graphic with a stage-sized hole in the middle, where the stage will show through. (Or that is what it seems to be, anyway).

What would be the simplest way to incorporate something like this into a Flash game? (In terms of highest childIndex etc). All help appreciated.

Actionscript delay inside function

I created a button in Adobe Animate which should, if you press him be exchanged with another button in a different color, after 1 second you should be forwarded to the previous scene.

My Code:

button_answer_2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToPreviousScene);
function fl_ClickToGoToPreviousScene(event:MouseEvent):void
{
    button_answer_2.visible = false;
    button_answer_2_red.visible = true;


        setTimeout(myDelayedFunction,3000);
        function myDelayedFunction(){
                MovieClip(this.root).prevScene();
            }
}

sadly the myDelayedFunction doesn't work because it is inside another fuction, I can't see analternative way. Could anyone help me? (I am not the best programmer so keep it simple if possible)

Thank you for your answer

dimanche 30 octobre 2016

how to display A is true in tihis code

var myTextField:TextField = new TextField();

var myTextFormat:TextFormat = new TextFormat();

addChild(myTextField);

myTextFormat.font = "Arial";

myTextFormat.size = 27;

myTextFormat.leftMargin = 5;

myTextField.border = true;

myTextField.width = 35;

myTextField.height = 35;

myTextField.x = 250;

myTextField.y = 11;

myTextField.type = "input";

myTextField.maxChars = 1;

myTextField.restrict = "^a-z";

myTextField.defaultTextFormat = myTextFormat;

enter image description here

need access to xml data but unsure where to build function

I have a course built in Lectora and I am trying to create an efficient way to store transcripts for each page of the course. Whenever a page from the course loads, a flash command is directed to a swf file along with a unique pageID. and a string (containing the appropriate transcript) is returned.

Here is a short version of my xml file transcripts.xml:

<?xml version="1.0" encoding="utf-8"?>
  <transcripts>
    <transcriptText pageID="c1p1">Transcript 1 text</transcriptText>
    <transcriptText pageID="c1p2">Transcript 2 text</transcriptText>
    <transcriptText pageID="c1p3">Transcript 3 text</transcriptText>
    <transcriptText pageID="c1p4">Transcript 4 text</transcriptText>
  </transcripts>

I am using the following XmlLoader.as file (which I found on the exchange, thank you) to load the xml.

package {

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

public class XmlLoader extends EventDispatcher {

    private var _xml:XML;

     public function XmlLoader(xmlPath:String){
        var xmlUrlRequest:URLRequest = new URLRequest(xmlPath);
        var xmlUrlLoader:URLLoader =  new URLLoader(xmlUrlRequest);
        xmlUrlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
    }

    private function xmlLoaded(e:Event):void{
        e.currentTarget.removeEventListener(Event.COMPLETE, xmlLoaded);
        _xml = new XML(e.currentTarget.data);
        dispatchEvent(new Event(Event.COMPLETE));
    }

    public function getXml():XML{
        return this._xml;
    }

}

}

And below is the code I have on the first frame of the flash file.

var myXML:XML;
var menuXmlList:XmlLoader = new XmlLoader("transcripts.xml");
menuXmlList.addEventListener(Event.COMPLETE, processXML);

function processXML(e: Event):void
 {
    myXML = (e.currentTarget.getXml());
 }

// this function is called as a Flash Command from within
// the course each time a new page loads. pageID is the unique
// identifier for that particular page.

function getTranscript(pageID: String):String
 {
    var pageNumber: String = pageID;
    var transcript: String = myXML.transcriptText.(@pageID == pageNumber);
    return (transcript);
 }

ExternalInterface.addCallback("getTranscript", getTranscript);

I have researched this a bit over the past few days and come to understand some of what is going on. The nature of asynchronous code means that the xml data hasn't made its way into myXML when getTranscripts() is called so trying to access myXML yields null and null reference warnings.

I think I need to hold the xml data in the class file until getTranscripts needs it. But I am not sure how to go about this. I've tried to write additional functions in the XmlLoader.as file but haven't met with any success.

Can anyone tell me if I am on the right track? Is the correct approach to create a method(s) in XmlLoader.as file that can be called bygetTranscripts() to return this value: myXML.transcriptText.(@pageID == pageNumber) pageNumber (being the unique identifier)?

Any thoughts or code examples would be greatly appreciated.

regards

AS3 Bitmaps and Filters

I feel like I'm missing something here, so hopefully this question will be answered quickly.

I'm beginning to use blitting to make my program more efficient due to the number of objects moving on the screen. And right now I'm testing out how to do the differently; I'm up to filters.

I'm trying to apply a simple glow filter using applyFilter(); The problems are:

a) It only works if I define the rectangle as bitmapData.generateFilterRect() which isn't an issue except

b) It ignores this and applies the filter while cropping the entire image. If you notice, only the top left corner is actually glowing, the rest is just cut off.

Original Grass Tile
Original Grass Tile

Grass Tile with Glow Filter applied
Grass Tile with Glow Filter applied

What am I missing here?

AS3 array indexOF

I am working on a game and have trouble with this array. There is all fruits on the stage which is generated from the array fruit. When the appel will hit the basket, we will count them. The melon is not to be counted. How do i find out if the current fruit is an appel or a melon?

var array_fruit:Array = new Array(appel1_mc, appel2_mc, melon_mc);

stage.addEventListener(Event.ENTER_FRAME, catchappels);

function catchappels(e:Event):void {

for (var i:int = appelsOnstage.length-1; i > -1; i--) { 
    var currentfruit:MovieClip = appelsOnstage[i];


    if (currentfruit.hitTestObject(basket_mc)) {        

        if(array_fruit.indexOf(currentfruit) == melon_mc ){
               trace("melon");
            } else {
               trace("no melon");
               appelsCollected++;
            }
    }
 }
}

How to make a menu for touchscreen (link buttons from scene to scene) with adobe flash CS6 actionscript 3.0

total newbie here. I've been using mouse events to link the menu buttons to jump from scene to scene or frame to frame, but since i want to make a menu for touchscreen, i would have to always double tap to actually activate the button. Is there anyway i can make the button respond with just one tap of a finger.

I've been using this code to jump from scene

movieClip_3.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_2);

function fl_ClickToGoToScene_2(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "Scene 2");
}

samedi 29 octobre 2016

FLASH AS3 looping scroll animation News ticker

As the title said, im trying to create a news ticker scrolling animation. Currently its just instant scrolling to the far end of the string.

import flash.net.URLRequest;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.display.Sprite; 
import flash.text.*;

var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://dust2.dk/Rss"));
function LoadXML(e:Event):void {
    xmlData = new XML(e.target.data);
    parseData(xmlData);

    dtext.wordWrap = false;
    dtext.scrollH = dtext.maxScrollH;

}

function parseData(xmlData:XML):void {
    //txtRSSFeed.appendText(xmlData);
        dtext.text = "";
    for (var i:int = 0; i<xmlData.channel.item.length(); i++){
        dtext.appendText(xmlData.channel.item[i].title + " - ");
        trace(xmlData.channel.item[i].title);
        if(i == xmlData.channel.item.length()){
            i = 0;
        }
    };

}

Is there any way to get the text to work as a marquee horizontal?

Actionscript 3 Dynamic line drawing with changing alpha

I have been creating a training tool for a customer in Flash, using Actionscript 3. In it i have to create one continuous line generated over time, whose alpha is controlled by a static object and its distance from a continuous moving object. The closer the two are, the stronger the line, the further the weaker. This alpha only effects the the line at the current time, leaving the historical alpha as it was when the the line was produced. The way I have currently made it is by generating lots of small lines, which when joined together make one big line. Thus each small line has a different alpha. The overall effect is to create fade ins and outs based on the distance between the two objects with historical alpha still showing. Does anyone out there have a better way of achieving this effect? Hopefully, I have not just confused everybody.

event.preventDefault is unclear for me even if I understand stopImmediatePropagation and stopPropagation

event.preventDefault seems to be hard to understand to me.(this is the dark side of AS3). :)

stopImmediatePropagation - stopPropagation methods are pretty easy to understand. Here's a test I made (which need just a copy/paste on the timeline) this may avoid You to spend too much time.

I just do not understand in which case preventDefault may be useful... If you have some suggestions or links, please could You give me some feedback?

Here is the code :

// This example is coded on the Timeline.
// The Stage must fit 550 * 400 pixels (default size).
import flash.display.DisplayObjectContainer;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;

// function to create a MovieClip and return it to a variable.
function createMC(target:DisplayObjectContainer):MovieClip{
    var mc:MovieClip = new MovieClip();
    target.addChild(mc);
    return mc;
}
// function that draws a Rectangle in the MovieClip of your choice.
function dRect(target:MovieClip,x:uint,y:uint,width:uint,height:uint,color:uint,alpha:Number):void{
    var g:Graphics = target.graphics;
    g.lineStyle(1,0x000000);
    g.beginFill(color,alpha);
    g.drawRect(x-width/2,y-height/2,width,height);
    g.endFill();
}
// event function that trace the properties of the Event.
function traceTarget(me:MouseEvent):void{
    trace(" *** event.phase = " + me.eventPhase + ", event.bubbles = " + me.bubbles);
    trace("me.target.name = " + me.target.name);
    trace("me.currentTarget.name(the listening object) = " + me.currentTarget.name);
    /*
    Use preventDefault and the events  for m1 AND this will be triggered.
    MOUSE_DOWN,setText will be called 2 times 1 time for this, the second time for m1!
    MOUSE_DOWN,traceTarget will be called 2 times 1 time for this, the second time for m1!
    */
    //me.preventDefault();
    /*
    Use stopPropagation to avoid that the same function is not called if an event occurs.
    MOUSE_DOWN,setText will be called !
    */
    me.stopPropagation();
    /*
    Use stopImmediatePropagation to avoid all the functions that another listener may trigger.
    MOUSE_DOWN,setText WILL NEVER BE CALLED because traceTarget has been called!
    stopImmediatePropagation will only allow the first listener (traceTarget).
    */
    //me.stopImmediatePropagation();
    trace(me.toString());
    // trace the Event that is triggered.
}
function setText(me:MouseEvent):void{
    tf_1.text = "me.target.name = " + me.target.name;
    tf_1.setTextFormat(tf);
    countText++;
    trace("setText("+ me.target + ") has been called " + countText + " time(s)");
    countText = 0;
}
/*
A counter to see how many times an Event method is triggered
*/
var countText:uint = 0;
/*
Declare a TextField
*/
var tf_1:TextField = new TextField();
this.addChild(tf_1);
tf_1.width = 300;
tf_1.height = 20;
tf_1.x = this.stage.stageWidth - this.stage.stageWidth/2 - tf_1.width/2;
tf_1.y = 30;
var tf:TextFormat = new TextFormat(null,16,0xff0000,true,null,null,null,null,TextFormatAlign.CENTER)
tf_1.text = "Click on a Square/Rectangle";
tf_1.setTextFormat(tf);
/*
Declare 4 MovieClips
3 MovieClips inside each other
    - m1 on "this" (root1 in this case).
    - m2 inside m1
    - m3 inside m2
1 MovieClip on "this" (root1 in this case).
*/
var m1:MovieClip
var m2:MovieClip
var m3:MovieClip
var otherClip:MovieClip
// Create the MovieClips
m1 = createMC(this);
m2 = createMC(m1);
m3 = createMC(m2);
otherClip = createMC(this);
// set the names for the MovieClip's
m1.name = "movieClip_1";
m2.name = "movieClip_2";
m3.name = "movieClip_3";
otherClip.name = "otherClip";
// Draw Rectangles in the MovieClip's
dRect(m1,275,200,100,100,0xff0000,1);
dRect(m2,275,200,50,50,0x00ff00,1);
dRect(m3,275,200,25,25,0x0000ff,1);
dRect(otherClip,100,200,50,50,0xff9900,1);
// Add a listener on m1 MovieClip.
m1.addEventListener(MouseEvent.MOUSE_DOWN,traceTarget,false);
m1.addEventListener(MouseEvent.MOUSE_DOWN,setText,false);
//  Add a listener on root (root1 in this case).
this.addEventListener(MouseEvent.MOUSE_DOWN,traceTarget,false);
this.addEventListener(MouseEvent.MOUSE_DOWN,setText,false);

If You could help me to understand the preventDefault method, I should be really happy.

Best regards. Nicolas.

vendredi 28 octobre 2016

Why dosent this custom library draw shapes? Actionscript 3

So I wrote this small utility, which I will be expanding, just to save some time, but it dosent seem to draw the shape, even though there are no compiler issues?

Custom class:

package ezd.easydraw
{
    import flash.display.MovieClip;
    import flash.display.Shape;

    public class EasyDraw extends MovieClip
    {
        public var _root:MovieClip = new MovieClip();
        public function DrawCircle(xpos:Number=200.0, ypos:Number=200.0, r:int=50, color:uint=0x00FF00, alph:Number=1.0) 
        {
            _root = MovieClip(_root);
            var circle:Shape = new Shape;
            circle.graphics.beginFill(color, alph);
            circle.graphics.drawCircle(xpos, ypos, r);
            circle.graphics.endFill();
            _root.addChild(circle);
        }
        public function DrawRect(xpos:Number=200.0, ypos:Number=200.0, w:int=50, h:int=50, color:uint=0x00FF00, alph:Number=1.0)
        {
            _root = MovieClip(_root);
            var rect:Shape = new Shape;
            rect.graphics.beginFill(color, alph);
            rect.graphics.drawRect(xpos, ypos, w, h);
            rect.graphics.endFill();
            _root.addChild(rect);
        }
    }
}

And the "main" window to draw the shapes:

import ezd.easydraw.EasyDraw;
stop();
var ezd:EasyDraw = new EasyDraw();
stage.focus = ezd._root;
ezd.DrawCircle(300, 300, 500);

What am I doing wrong?

NetStream.currentFps vs Camera.currentFps (Flash As3)

I am using a flash (pure as3) client and Wowza to create live streaming over RTMP protocol. The input for the publishing stream is taken from the camera (at 30 FPS). I encode the video using H264.

Intuitively I would say that stream's current fps should be lower or equal to camera's current fps. But this doesn't always happen. Sometimes stream's fps is higher than camera's (even doubles). I thought that the buffer might influence this. But after several tests with different buffer sizes it seems that the buffer has nothing to do with it.

I noticed that the one that influences the difference between stream current fps and camera current fps is actually camera's key frame interval. With a keyframe interval at 1 (so every frame is a key frame and the camera at 30 fps), stream's current fps was around 60 (so it doubled). Having the interval at 30 made the values to be almost equal. Tried values in between and made me think that a key frame is counted as 2 for the stream's current fps or that the encoder introduces another frame for every keyframe.

I also changed the encoder to Sorenson Spark (H.263) and camera current fps, stream fps became equal (30) even with a key frame interval at 1. This made me think that it has to do something with the H.264 encoder.

I have to add that on the viewer side I see no more than camera's fps (30) even if the stream's current fps is at 60.

Why the H264 encoder works this way? What's exactly the mechanism which makes stream's current fps to be higher than camera's current fps? Why on the viewer side you see only at most camera's current fps (maximum 30 FPS)?

I would really appreciate an answer on this! Thank you!

saving option is shown in pc but not in a mobile when using filereference in as3

I made audio recorder application in as3 flash.it works fine in a flash and i save that audio file using fileReference in as3. When record completed,it shows save dialogue box in pc. But when i installed this app in mobile.Audio file is not saved. Save dialogue box doesn't appear in mobile ."app stopped working" problem appears. If Anyone knows solution to this problem,then please tell me.thanks in advance to each and everyone. Code is as folllow-

function recordComplete(e: Event = null): void {
var fileTemp = File.applicationStorageDirectory.resolvePath("SAMEER/");
fileReference.save(recorder.output, "recording.mp3");
recButton.addEventListener(MouseEvent.CLICK, startRecording);
}

jeudi 27 octobre 2016

Flash CS6 AS3 Air 3.2 for Android - Swipe to go to next/previous frame

I'm using this code from the Code Snippets to move to the next frame in the timeline when I swipe the touchscreen:

stop();

Multitouch.inputMode = MultitouchInputMode.GESTURE;

stage.addEventListener(TransformGestureEvent.GESTURE_SWIPE, fl_SwipeToGoToNextPreviousFrame);

function fl_SwipeToGoToNextPreviousFrame(event:TransformGestureEvent):void

{
    if (event.offsetX == 1)
    {
        prevFrame();
    }
    else if (event.offsetX == -1)
    {
        nextFrame();
    }
}

The timeline has a motion tween that moves a wide image of a street across the stage to give the impression that the user is moving along the street.

This code only moves the timeline one frame at a time though which means it takes forever to play the entire timeline.

How would I achieve a more fluid motion where multiple frames are progressed and the number of frames progressed is dependant on the duration and speed of the swipe?

Do I need a completely diffeent code to do that?

Using a symbol buttons as a keyboard buttons in a mobile AIR application

I have four buttons in my stage and I would like to set every button with its equivalent in keyboard buttons, you can say like a shortcut buttons. this is the name instance of my buttons with keyboard buttons. - btn1 for Left arrow - btn2 for Right arrow - btn3 for Up arrow - btn4 for Down arrow is there any way to do this? Thanks.

SharedObject.flush() not working on android 4.2 - Adobe air CS6

I have an Air application working on iOS and android. At some time, i am saving the high score using the following line :

mySharedObject.data.score = score;
mySharedObject.flush();

This is working fine on all iOS devices, and all the android devices running Android OS 5.0 and above. I am using the AIR 23 SDK. Is there any reason why the score is not saving for those particular devices? Should i limit the Android OS capability to 5.0 and above or is there any workaround i am missing?

actionscript issue adding shape to container

I don't know how to describe this problem but I will try to be clear enought. I am doing an actionscript exercise where I have a DisplayObjetct Container defined as Sprite, and what I want is to add ramdomizely circles with a random radio length between 50 and 100.

The Container called "gameZoneContainer_sp" has been added to the displaylist in the Main class, and everytime the user change the size of the stage the container set its new values of width and height.

Here is the code of what i am saying:

private function refreshScreen(ev:Event= null ):void{

        // Remember: we can know stage dimensions accessing to:
        // stage.stageWidth
        // stage.stageHeight

        //CONSTANTS DEFINITION OF MARGIN
        const margen:Number=25;

        //LOCAL VARIABLES DEFINITION
        var cercleWidth:Number, cercleHeight:Number;
        var invaderWidth:Number, invaderHeight:Number;
        var containerWidth:Number, containerHeight:Number;
        var logoWidth:Number, logoHeight:Number;

        //STORING DIMENSIONS
        cercleWidth=addCercle_bt.width;
        cercleHeight=addCercle_bt.height;
        invaderWidth=addInvader_bt.width;
        invaderHeight=addInvader_bt.height;
        containerWidth=gameZoneContainer_sp.width;
        containerHeight=gameZoneContainer_sp.height;
        logoWidth=logoUOC_sp.width;
        logoHeight=logoUOC_sp.height;

        //SET HORIZONTAL POSITION OF THE ELEMENTS
        addCercle_bt.x=(stage.stageWidth/2)+margen;
        addInvader_bt.x=(stage.stageWidth/2)-(invaderWidth+margen);
        gameZoneContainer_sp.x=margen;
        logoUOC_sp.x=stage.stageWidth-(logoWidth+margen);

        //SET VERTICAL POSITION OF THE ELEMENTS
        addCercle_bt.y=stage.stageHeight - (cercleHeight+margen);
        addInvader_bt.y=stage.stageHeight-(invaderHeight+margen);
        gameZoneContainer_sp.y=logoHeight+margen*2;
        logoUOC_sp.y=margen;

        //SET DIMENSIONS OF CONTAINER gameZoneContainer_sp
        gameZoneContainer_sp.width=stage.stageWidth-(margen*2);
        gameZoneContainer_sp.height=stage.stageHeight-(margen*4)-invaderHeight-logoHeight;

    }

    /* THIS METHOD ADD A CIRCLE TO THE CONTAINER  gameZoneContainer_sp */
    private function addCercle(ev:MouseEvent):void {
        // Create new instance of Cercle
        // and add it to gameZoneContainer_sp

        //CONSTANT DEFINITIONS
        const minRadio:Number=50, maxRadio:Number=100;

        //LOCAL VARIABLES DEFINITIONS OF RADIO, COLOR AND CIRCLE
        //THE RADIO CHOOSE A RANDOM VALUE BETWEEN 50 AND 100
        var radio:Number=minRadio+(maxRadio-minRadio)*Math.random();
        var color:uint=Math.random() * 0xFFFFFF;
        var cercle:Cercle=new Cercle(color,radio);


        //
        var minPosX:Number=radio;
        var maxPosX:Number=gameZoneContainer_sp.width/2;
        var minPosY:Number=radio;
        var maxPosY:Number=gameZoneContainer_sp.height-(minPosY);


        // SET POSITION OF THE CIRCULE INSIDE THE CONTAINER
        cercle.x= minPosX + (maxPosX-(2*minPosX))*Math.random();
        cercle.y= minPosY + (maxPosY-(2*minPosY))*Math.random();
        cercle.drawCercle();
        gameZoneContainer_sp.addChild(cercle);
        refreshScreen(ev);

        //TRACING RESULTS...
        trace ("Added cercle!");    
        trace ("alto del contenedor: "+gameZoneContainer_sp.height);
        trace ("Posicion x: "+cercle.x);
        trace ("radio: "+radio);    
    }

        //DEFINITION OF THE CIRCLE CLASS
public class Cercle extends Sprite {
        private var _color:uint;
        private var _radio:Number;

        public function Cercle(color:uint,radio:Number){
            super();
            /* THE CLASS ACCEPT HEX VALUES.*/
            _color= color;
            _radio=radio;
            init();
        }

        public function init():void{
            drawCercle ();
        }
        //METHOD TO DRAW A CIRCLE
        public function drawCercle():void{
            var circle:Shape=new Shape();
            circle.graphics.beginFill(_color,1);
            circle.graphics.drawCircle(0,0,_radio);
            addChild(circle);

        }

    }

Here is my problem: When I add a circle it seems to be fine until I change the dimensions of the windows (the scene). Everytime I update the dimensions, the event execute the method refreshScreen from the main class which update the dimensions and positions of all elements in scene, but after that if i add a new circle, it change the container, and that is wrong because what I want is to add the circle IN the container.

Hope is not too long. Please any help would be great! Thank you in advance!!

Background processes continue after removing children

I made this menu that launches at the start-up of my program. (Main.as: launches mainMenu.as, mainMenu.as: launches other instances inside itself.) This mainMenu has a button on top which says "new game", I want this button to take me to the next menu, thus removing the mainMenu-instance.

I did successfully remove the mainMenu. However, I reviled by using trace() inside one of my classes that a function was still running in the background. (This was the class of an instance inside the mainMenu-instance).

I have tried both to eliminate the mainMenu-instance by using:

>this.parent.removeChild(this);
>trace("all processes shall now be over");

and, by removing all the children inside mainMenu by using:

>while (this.numChildren > 0) {
>>this.removeChildAt(0);
>}
>trace("there shall be nothing going on after this");

This has removed all the visual stuff from the screen. But a timer-loop-function from one of the instances inside mainMenu is still running in the background, once again reviled by trace(). All these children should be eliminated at this point, so how come these processes are still running? This noobie needs help.

mercredi 26 octobre 2016

Have the netstream play the stream with no video attached with minimal CPU usage?

Problem: I have a local webpage (any browser running on Windows 7) with many Flash Players that connect to live streams and play the stream but it does not attach a video object to the netstream.

All I want is for the netstream to play the stream but not display the video which works but I'm surprised the CPU usage is still showing the same usage as if the video object was attached.

Question: Is there a way to have the netstream play the stream with no video attached with as minimal of CPU usage as possible? I've set the framerate to 4 with no change. I've read a lot about throttling the renderer but it seems I can't control when to activate it.

By the way, I only have a stage in my app and nothing else.

Thank you for your time and help!

Make Phone Calls skipping dialer on Adobe AIR on Android

I am creating a android app on adobe air. I have a button in my app, clicking on which I need to call to a number skipping the dialer and once the call finishes I want the control to return to my app and record the call duration in local db. Someone please help me with code/links to the information.

Currently I am using following code to call the number which goes through the dialer,

navigateToURL(new URLRequest("tel:"+telNumber.text));

How can I only drag obj.mc up and down

Anyone help me please. I'm totally new to AS3.

I have an mc called obj.

How can I only drag it only : up and down?

Here is the code I found somewhere on the internet.

import flash.events.MouseEvent;
import flash.geom.Point;
import flash.events.Event;

var destination:Point=new Point();
var dragging:Boolean=false;
var speed:Number=5;
var offset:Point=new Point(); // our offset

obj.addEventListener(MouseEvent.MOUSE_DOWN,startdrag);
stage.addEventListener(MouseEvent.MOUSE_UP,stopdrag);
obj.addEventListener(Event.ENTER_FRAME,followmouse);

function startdrag(e:MouseEvent):void{
   offset.x=obj.mouseX*obj.scaleX;   // record offset (pt obj is dragged 
   offset.y=obj.mouseY*obj.scaleY;
   dragging=true;
}

function stopdrag(e:MouseEvent):void{
   dragging=false;
}

function followmouse(e:Event):void{
   if(dragging){
      destination.x=mouseX;
      destination.y=mouseY;
   }
   obj.x-=(obj.x-(destination.x-offset.x))/speed;   // apply offset
   obj.y-=(obj.y-(destination.y-offset.y))/speed;
}

Add hyperlinks to SWF buttons

I have an SWF file which I downloaded off the internet for studying purposes: http://binw.net/externalUIs/campaigns/skylandersSuperchargers/SkylandersSuperchargersMap_26_10_15.swf

There are different "locations" on the SWF file and I believe it is a map - for example, there's a fountain, a racing track, a tree and a castle. What I need to do is make all the different locations redirect to a different hyperlink.

I had a look at How to edit redirect link on an SWF Flash file? and it suggested that I download the trial version of Flash Decompiler which I have done but I am lost at what to do subsequent to this.

mardi 25 octobre 2016

How can I use "ease" for smoother dragging?

I have dragging mc called "box" but the dragging is not smooth at all.

So how can I make it smoother by using "ease" var.

I'm trying to use "/ease" anywhere but not work.

var topY:int = stage.stageHeight - box.height;
var botY:int = 0;


box.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
box.addEventListener(MouseEvent.MOUSE_UP, onUp);
var constrainY:Rectangle = new Rectangle(box.x, topY ,0, box.y+ (box.height-stage.stageHeight)  );
var dragxy:String = "";
function onDown(e:MouseEvent):void
{
    dragxy = mouseX + "_" + mouseY;
    e.currentTarget.startDrag(false, constrainY);
    removeEventListener(MouseEvent.MOUSE_DOWN, onDown);
    addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onUp(e:MouseEvent):void
{
    e.currentTarget.stopDrag();
    addEventListener(MouseEvent.MOUSE_DOWN, onDown);
    removeEventListener(MouseEvent.MOUSE_UP, onUp);
}

Calling a function in android activity in AS3 native extensions

I have an android ANE, and when the ANE initializes I start a new CustomActivity (extends Activity) which has all my custom logic for the ANE.

This is how I start the activity in my CustomExtensionContext (extends FREContext) class :

Intent intent = new Intent(getActivity().getApplicationContext(), CustomActivity.class);
getActivity().startActivity(intent);

Now, in my CustomAcivity, I have some other public methods which I want to call through my as3 code. I have created FREFunction classes and have added these functions to the HashMap. And I know how I can call the function from the as3 side.

What i dont know is, how to call some public method of CustomActivity class from my CustomExtensionContext, as I dont have any reference to its object ??!!

(new to Android, I am an AS3 developer)

Thanks

Can't call WebAPI with valid token in AS3

I have an ActionScript3 game that needs to make calls to a Web api. I can successfully get a token. After getting the token, I make a call which requires authentication but I always get {"Message":"Authorization has been denied for this request."}.

I can call the same api using PostMan without any issues. Here's the headers I'm adding.

urlRequest.requestHeaders.push(new URLRequestHeader("Content-Type", "application/json"));
urlRequest.requestHeaders.push(new URLRequestHeader("Authorization", "Bearer " + accessToken));

Any ideas?

Canceling a state transition and go directly to another view

I have a skin with 3 states. I may have more states in the future. But it's a tool bar with normal state, and then an expanded view where only one expanded view should be visible at a time.

When I had two states I could easily transition between the two using the transition code below. But now that I have three states the secondary state is not closed. If I'm in a secondary state I want to close out of it first.

Here is my code from the skin class. This may work in an application:

<s:transitions>
    <s:Transition fromState="normal" toState="*">
        <s:Sequence duration="250">
            <s:Resize target="{this}"/>
            <s:AddAction target="{linkToolButton}"/>
            <s:Fade target="{linkToolButton}"/>
        </s:Sequence>
    </s:Transition>

    <s:Transition fromState="linkView" toState="*">
        <s:Sequence duration="250">
            <s:Fade target="{linkToolButton}"/>
            <s:Resize target="{this}"/>
        </s:Sequence>
    </s:Transition>

    <s:Transition fromState="imageView" toState="*">
        <s:Sequence duration="250">
            <s:Fade target="{imageToolButton}"/>
            <s:Resize target="{this}"/>
        </s:Sequence>
    </s:Transition>
</s:transitions>

<s:states>
    <s:State name="normal"/>
    <s:State name="linkView"/>
    <s:State name="imageView"/>
</s:states>


<s:VGroup width="100%">
    <s:HGroup width="100%" >    
        <s:Button label="Normal View" width="20" />
        <s:Line height="100%">
            <s:stroke>
                <s:SolidColorStroke color="#B3C2B8"/>
            </s:stroke>
        </s:Line>
        <s:Button id="gotoLinkView" width="23"/>
        <s:Line height="100%">
            <s:stroke>
                <s:SolidColorStroke color="#B3C2B8"/>
            </s:stroke>
        </s:Line>
        <s:Button id="gotoImageView" width="23" icon="@Embed('richTextEditorClasses/icons/image.png')"/>
        <s:Line height="100%">
            <s:stroke>
                <s:SolidColorStroke color="#B3C2B8"/>
            </s:stroke>
        </s:Line>
    </s:HGroup>

    <s:Button id="linkViewButton" 
                  includeIn="linkView" 
                  itemCreationPolicy="immediate" width="100%"/>

    <s:Button id="imageViewButton" 
                         includeIn="imageView" 
                         itemCreationPolicy="immediate"
                         width="100%"/>
</s:VGroup>

Make Phone Calls on Adobe AIR desktop application

I try to launch a phone call from my desktop air application. I found a partial solution with navigateToUrl

var urlToCall:String="tel:+33134000066";
var request:URLRequest = new URLRequest(urlToCall);
navigateToURL(request);

But, I'd to find a free solution : in France hangout or Skype need credit to work. So do you know a free solution or api to launch phone call.

Best regards

Get text outline in as3

I have a flash application and i am trying to create a hand write effect, it will have to draw the outline of the text , so i need the outline of the text , I could have got it if it is predefined fonts , but my users can upload fonts too , so is there any way i can extract outlines of a text in run time? any help is appreciated

i know about readGraphicsData, but it wont help!

`please 
help any help would be appreciated`

adding the following code because it is not allowing me to post a question , so this is some random code , just ignore it

<?xml version="1.0"?>
<svg xmlns="http://ift.tt/nvqhV5"
 width="100px" height="30px" viewBox="0 0 1000 300">

  <text x="250" y="150" 
        font-family="Verdana" 
        font-size="55">
    Hello, out there
  </text>

  <!-- Show outline of canvas using 'rect' element -->
  <rect x="1" y="1" width="998" height="298"
    fill="none" stroke-width="2" />
</svg>

How to play sound and stop sound using combobox[AS3]?

in this code all sounds play togather..I want when I play sound1 sound2 stop ..when I play sound2 sound1 stop thanks for anyone can help

    stop();

import flash.events.Event;
import flash.media.Sound;



var mysound1:MYSf = new MYSf
var mysound2:sounda = new sounda

combobox.addItem( { label: "sound1" } );
combobox.addItem( { label: "sound2" } );


combobox.addEventListener(Event.CHANGE, myq);

function myq (e:Event):void
{
    if (combobox.selectedItem.label == "sound1")
    {
         mysound1.play();
        mysound2.stop();
    }
    if (combobox.selectedItem.label == "sound2")
    {
        mysound2.play();
         mysound1.stop();

    }


}

lundi 24 octobre 2016

Automatic Level Generation from Array

So, I am trying to make the stages for the level in my game automatically generated. I made an array (note, the amount of "tiles" on the screen is 16x16):

var background:Array=new Array(
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
)

And as you can probably tell, each 1 or 0 corresponds to if the tile is one thing or another (there or not there in this scenario).

I am pretty bad at the next part that I did.

I decided to make this using http://ift.tt/2eN4bME's method (kinda).

var bkgblocks:Sprite=new Sprite();
var bkgblocksw:Number=stage.stageWidth/16
var bkgblocksh:Number=stage.stageHeight/16

//the blocks are 45 pixels wide and tall

var row:int=0;
for(var i:int=0; i<background.length;i++){
    if((i+1)/16==int((i+1)/16)){
        //if i is divisible by 16
        row++
    }
    if(background[i]==1){
        bkgblocks.graphics.beginFill(0x000000)
        bkgblocks.graphics.drawRect(I have no idea what to do here ,row*stage.stageHeight/16,bkgblocksw,bkgblocksh); 
        bkgblocks.graphics.endFill()
        addChild(bkgblocks)
    }
}

As you can see, I have no idea how or where to place the blocks!

I have where to place their y coordinate, but the x is way too confusing.

I thought I could do something like this

i*(45/(row+1))

but that messed up completely. This is more of a math question, I'm sorry, but if anybody can (or has) figure this out, I would appreciate it.

WebRTC (for video chatting) Adobe AIR ANE for android and iOS

Is there some ANE or possible other solution for using WebRTC (mainly for video chat) in Adobe AIR (AS3) for mobile ? There are some third party sdks like Twilio or TokBox but they only provide native solutions.

I really need a solution for having cross-platform (or any kind of) good quality video conferencing/chatting library for AIR (android and iOS both).

Thanks

AS3: alternative to a sequence of setters between packages?

in my project im trying to have two packages communicate with one another to set a variable. the first package is "locations" and the second package is "interface".

the interface contains an interface class, which contains a textbox class. the textbox class contains a font class (i made a special font class so the font animates as it displays) which is actually contained in the root folder with the main doc. this font class displays text through a dynamic textfield.

inside of the locations package is the location class. the location subclasses (which represent in-game locations) have many objects the user can click. once these objects are clicked, a message is to be sent from the location class to the font class, which will display some text. so far, my limited knowledge of OOP design has lead me to write this:

    package Locations {
    public class _location extends MovieClip { 
    //constructor, etc...
    protected function setMyGuy(shyType:*, xCoor:int, yCoor:int, dialoguePassed:String):void {
        addChild(shyGuy);
        shyGuy.x = xCoor;
        shyGuy.y = yCoor;

        //when character is clicked, use the dialogue passed into the function from elsewhere...
        shyGuy.addEventListener(MouseEvent.CLICK, shyResponse(dialoguePassed)); 
    }

    protected function shyResponse(dialogueRecieved:String):Function {
        return function(e:MouseEvent):void {
            //...to tell the interface class (child of location class)...
            myInterface.uiInterfaceText = dialogueRecieved;
        }
    }}}

    //...to tell the textbox class...
    package Interface {
    public class ui extends MovieClip {
    public function set uiInterfaceText(dialogue:String) {
        textbox.interfaceText = dialogue;
    }}}

    //...to tell the font class...
    package Interface {
    public class interfaceTextbox extends MovieClip{
    public function set interfaceText(dialogue:String):void {
        tf.myDialogue = dialogue;
        tf.removeText(5);
    }}}
    //...to change the dialogue being displayed to what was originally passed by the location class 
    package {
    public class strangersFont extends MovieClip{
    public function set myDialogue(dialogue:String):void {
        tf.text = dialogue;
    }}}

as you can see this is the most convoluted bullshit. how do i reach straight into the font class from the location class when the font class is not a direct child of the location class? my understanding of scope is a budding flower; please water it.

Going back to the last frame when pressing the 'back' button on android

I've got an AIR app with 30 frames. The user can navigate in the app but I'd like to add a function that allows him to press the "back" button on Android devices. When he'll do that, he will go back to the frame he was (NOT prevFrame but the frame he was).

Example, the user is on frame 25. Then goes to frame 12. If he clicks on the back button, he will go back to frame 25.

I've managed to activate the back button for Android :

    NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, checkKeypress, false, 0, true);

    function checkKeypress(event: KeyboardEvent): void {
    if (event.keyCode == Keyboard.BACK) {
    //So, what should I put here for going back to the last frame viewed ? 
    }
}

Going back to the last frame when pressing the 'back' button on android

I've got an AIR app with 30 frames. The user can navigate in the app but I'd like to add a function that allows him to press the "back" button on Android devices. When he'll do that, he will go back to the frame he was (NOT prevFrame but the frame he was).

Example, the user is on frame 25. Then goes to frame 12. If he clicks on the back button, he will go back to frame 25.

I've managed to activate the back button for Android :

    NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, checkKeypress, false, 0, true);

    function checkKeypress(event: KeyboardEvent): void {
    if (event.keyCode == Keyboard.BACK) {
    //So, what should I put here for going back to the last frame viewed ? 
    }
}

AS3: TypeError: Error #1009: Cannot access a property or method of a null object reference

I've been working on a flash game for an assignment and it's been a real headache so far. The game's relatively simple, collect items (mementos), avoid enemies or lose health (sanity), collect all items on the screen to level up (items, player and enemies reset, score remains the same), get hit 5 times and you get the game over screen.

I've having an annoyingly odd error. Getting game over with no items doesn't give any errors and resets the game fine (seemingly), but the issues are:

*Having any items when getting game over results in Error 1009.

*Clicking the exit game button with any items results in Error 1009.

*Collecting all the items should give the "lvlUp" function, but nothing happens, the if statement never triggers.

I've spent a good day or so on this issue and came pretty close to breaking the entire thing a few times, so I decided to consult here with experienced coders.

Apologies in advance for messy code, I've only just started using AS3

Game document class code:

package 
{

import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.geom.Rectangle;
import player;

public class Memento extends MovieClip
{
    //importing required variables
    private var onScreenContent:Array;
    private var playerSkill:int;
    private var myXY:Array;
    private var mySpeed:int;
    private var border:Rectangle;
    private var myMaxItems:int;
    private var numItems:int;
    private var numEnemies:int;
    private var maxEnemies:int;
    private var characterMC:player;
    public var sanity:int;
    public var mementos:int;
    public var currentMementos:int;

    //CONSTRUCTOR
    public function Memento()
    {
        trace("initialising DOS game");
        //simulates a selected skill level  
        playerSkill = 3;
        sanity = 5;
        mementos = 0;
        onScreenContent = new Array  ;
        border = new Rectangle(30,180,870,750);
    }

    //code to add character into game at correct position
    private function addCharacter():void
    {
        trace("Adding the character");
        //set the initial values to character starting pos
        var myXY:Array = [480,900];
        var mySpeed:int = playerSkill + 6;
        //create and add a new player to screen
        characterMC = new player(myXY,border,mySpeed);
        addChild(characterMC);
        characterMC.focusRect = false;
        stage.focus = characterMC;
    }//end function addCharacter
    //code to add items into game
    private function addItems():void
    {
        trace("Initialising items");
        //amount of items
        var myMaxItems:int = playerSkill + 1;
        //adding the items one at a time
        for (var numItem:int = 0; numItem < myMaxItems; numItem++)
        {
            var thisItem:collect = new collect(border,playerSkill,characterMC);
            thisItem.name = "Item";
            //adding item to stage
            onScreenContent.push(thisItem);
            addChild(thisItem);
        }//end for statement
    }//end function addItems
    //code to add enemies into game
    private function addEnemy():void
    {
        trace("Adding Enemies");
        //setting initial number of enemies to match game/skill level
        var maxEnemies:int = playerSkill + 1;
        //adding enemies one by one using a loop
        for (var numEnemies:int = 0; numEnemies < maxEnemies; numEnemies++)
        {
            //creating a new enemy
            var thisEnemy:enemy = new enemy(border,playerSkill,characterMC);
            thisEnemy.name = "Enemy";
            trace("adding enemies to stage");
            onScreenContent.push(thisEnemy);
            addChild(thisEnemy);
        }
    }//end function addEnemy
    //code to update game scores
    public function updateScores(myMC: MovieClip):void
    {
        //change player score if they collide with enemy or item
        mementos +=  myMC.scoreMod;
        sanity +=  myMC.healthMod;
        if (currentMementos == 4)
        {
            trace("lvlup");
            levelUp();
            currentMementos = 0;
        }//end if statement
        if (myMC.name.indexOf("item") != -1)
        {
            var myIndex:int = onScreenContent.indexOf(myMC);
            onScreenContent.splice(myIndex, 1);
            currentMementos++;
        }//end if statement
        trace("updating player score");
        //run updatescores function
        displayScores();
        //run gameover check
        if (sanity <= 0)
        {
            trace("game over prompted");
            gameOver();
        }//end if statement
    }
    //function to update scores
    private function displayScores():void
    {
        //update dynamic text fields
        lifeDisplay.text = "*" + sanity;
        scoreDisplay.text = "Mementos: " + mementos;
        trace("displaying updated scores");
    }
    //function to level up
    private function levelUp():void
    {
        // resetting all items
        clearObjects();
        removeChild(characterMC);
        playerSkill +=  1;
        //resetting game stage
        addCharacter();
        addItems();
        addEnemy();
    }

    public function clearObjects():void
    {
        //removing all remaining game objects
        for each (var myObj in onScreenContent)
        {
            myObj.removeAsset();
            myObj = null;
        }

        // reset the array for next level
        onScreenContent = new Array();
    }

    //function to return from map stage back to main menu
    function exitMap(event:MouseEvent):void
    {
        gotoAndStop(1);
        //removing player
        removeChild(characterMC);
        clearObjects();
        mementos = 0;
        sanity = 5;
        currentMementos = 0;
    }//end function exitMap
    //function to execute game over
    private function gameOver():void
    {
        //game over script
        trace("game over");
        gotoAndStop(4);
        clearObjects();
        removeChild(characterMC);
        mementos = 0;
        sanity = 5;
        currentMementos = 0;
    }
}//end class
}//end package

Enemy class code:

package 
{

import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.geom.Rectangle;

public class enemy extends MovieClip
{

    private var borderEnemy:Rectangle;
    private var charNum:int;
    private var charSpeed:int;
    private var charDir:int;
    private var offset:int;
    private var characterMC:MovieClip;
    public var healthMod:int;
    public var scoreMod:int;

    //CONSTRUCTOR FUNCTION
    public function enemy(myBorder:Rectangle, mySkill:int, player:MovieClip)
    {
        //set values
        trace("initialising an Enemy");
        mySkill = 3;
        characterMC = player;
        borderEnemy = new Rectangle(50,180,840,750);
        //setting constraing area
        borderEnemy = myBorder;
        offset = 20;
        //values of lives/scores
        healthMod = -1;
        scoreMod = 0;
        //nasty type linked to mySkill
        charNum = Math.ceil(Math.random() * (mySkill + 2));
        charSpeed = charNum + 1;
        //what can I hit?
        //eventlistener: starts code when character enters stage
        addEventListener(Event.ADDED_TO_STAGE, initEnemy);
        addEventListener(Event.ENTER_FRAME, checkCollision);
    }//end function enemy

    //function to initiate enemy
    private function initEnemy(evt:Event):void
    {
        //displaying the enemy frame (appearence) according to charNum
        gotoAndStop(charNum);
        //setting item positon, linked to function
        setPosition();
        //start movement of enemy, linked to function
        addEventListener(Event.ENTER_FRAME, moveEnemy);
        //remove unneeded listener after initiation
        removeEventListener(Event.ADDED_TO_STAGE,initEnemy);
    }//end function initEnemy

    //function to set enemy position
    private function setPosition():void
    {
        //setting enemy positions
        //trace("setting enemy position");
        //code to determine enemy direction
        charDir = Math.floor(Math.random() * 2);
        //trace("charDir value is " + charDir);
        //code to determine enemy location (vertically)
        var myRand:int = Math.ceil(Math.random() * 8) * (Math.ceil(Math.random() * 5) + 2);
        if (charDir < 1)
        {
            //trace("char entering from left");
            //random option 1: character appears from the left
            charDir = 1;
            this.x = borderEnemy.left - offset - myRand;
            this.scaleX = 1;
        }
        else
        {
            //trace("char entering from right");
            //random option 2: character appears from the right
            charDir = -1;
            this.x = borderEnemy.right + offset + myRand;
            this.scaleX = -1;
        }
        //set verticle position using myRand
        var myHeight:int = borderEnemy.bottom - borderEnemy.top - offset * 1;
        this.y = Math.ceil(Math.random() * myHeight) + borderEnemy.top * 1;
    }//end function setPosition

    //function to move enemies
    private function moveEnemy(evt:Event):void
    {
        if (charDir < 1)
        {
            this.x +=   -  charSpeed - 10;
        }
        else
        {
            this.x +=  charSpeed + 10;
        }
        //reset character as it hits the border
        if (this.x < borderEnemy.left - 40 || this.x > borderEnemy.right + 40)
        {
            setPosition();
        }
    }//end function moveEnemy

    //function to check for collisions between player and enemies
    private function checkCollision(evt:Event):void
    {
        //detecting if enemy has hit the player character
        if (this.hitTestObject(characterMC))
        {
            trace("Hit an enemy");
            MovieClip(root).updateScores(this);
            setPosition();
        }//end if statement
    }//end function checkCollision
    //function to remove enemies from map
    public function removeAsset():void
    {
        // remove event listeners and the item
        removeEventListener(Event.ENTER_FRAME, checkCollision);
        //removeEventListener(Event.ENTER_FRAME, moveEnemy);
        this.parent.removeChild(this);
        trace("removing the enemies");
    }//end function removeAsset
}//end class
}//end package

Item class code (collect)

package 
{

import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.geom.Rectangle;

public class collect extends MovieClip
{

    private var itemNum:int;
    private var borderCollect:Rectangle;
    private var frameNum:int;
    private var characterMC:MovieClip;
    public var healthMod:int;
    public var scoreMod:int;

    public function collect(myBorder:Rectangle, mySkill:int, player:MovieClip)
    {
        borderCollect = new Rectangle(30,180,870,750);
        characterMC = player;
        healthMod = 0;
        scoreMod = 1;
        //constructor code
        trace("Initialise an Item");
        //constraint area for item spawn
        var borderCollect = myBorder;
        var offset = -200;
        //which item is spawned - based on the player skill variable
        var itemNum = Math.ceil(Math.random() * mySkill);
        var frameNum = Math.ceil(Math.random() * 3);
        //start process once item appears on stage
        addEventListener(Event.ADDED_TO_STAGE,initItem);
        addEventListener(Event.ENTER_FRAME, checkItems);
    }//public function "collect" end, what is initiated by the class

    private function initItem(evt:Event):void
    {
        //display frame based on itemNum
        gotoAndStop(frameNum);
        trace("selecting item frames");
        //tun position item function
        setPosition();
        trace("setting item positions");
        //remove no longer needed event listener
        removeEventListener(Event.ADDED_TO_STAGE,initItem);
    }//function initItem end

    private function setPosition():void
    {
        var myBorder = new Rectangle(50,180,800,500);
        var offset = 100;
        //positioning the Item according to borders
        trace("setting positions for items");
        var myWidth:int = myBorder.right - myBorder.left - offset;
        this.x = Math.ceil(Math.random() * myWidth) + myBorder.left * 1;
        var myHeight:int = myBorder.bottom - myBorder.top - offset;
        this.y = Math.ceil(Math.random() * myHeight) + myBorder.top * 1;
    }//function setPosition end

    private function checkItems(evt: Event):void
    {
        // hit the character 
        if (this.hitTestObject(characterMC))
        {
            trace("Got an Item");
            MovieClip(root).updateScores(this);
            removeAsset();
        }//end if statement
    }//end function checkCollision

    public function removeAsset():void
    {
        // remove event listeners and the item
        removeEventListener(Event.ENTER_FRAME, checkItems);
        this.parent.removeChild(this);
        trace("removing an Item");
    }//end function removeMe

}//class end

}//package end

Error (gameover with any items collected)

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at collect/removeAsset()[H:\DIG MEDIA Post CHris\Memento - items added\collect.as:77]
at Memento/clearObjects()[H:\DIG MEDIA Post CHris\Memento - items added\Memento.as:140]
at Memento/gameOver()[H:\DIG MEDIA Post CHris\Memento - items added\Memento.as:165]
at Memento/updateScores()[H:\DIG MEDIA Post CHris\Memento - items added\Memento.as:111]
at enemy/checkCollision()[H:\DIG MEDIA Post CHris\Memento - items added\enemy.as:113]

The addItem, addEnemy, addItems and such are also placed in the .fla frames connected to buttons instead of the document class. I know it's bad practice but they've been there since the start and when I tried moving them it caused a lot of issues.

In any case, thanks so much to anyone willing to sift through my (horribly formated) code to find the (likely very stupid) mistake I've made, and again I'm sorry for the massive blocks of code, I'm just not sure where I went wrong.

Adobe AIR NativeProcess not sending input

There's the problem: I am trying to get a Adobe AS3 app made in Flash Builder communicate with the console. My console application uses .NET 4.5.2, but it does not seem to be reading the input. It works with a .NET 3.5 console app, but for me it is essential for it to work with .NET 4.5.2.

This person has a similar problem but was not able to solve it.

Let me know if anyone knows a way around this.

HAXE - Check if variable exists on class, if so, modify the value of this variable (TL;DR at bottom)

Hello people of StackExchange, this is my first post, as I've tried my best to solve this on my own, and I cannot find a really good solution that matches the solution I have in AS3.

AS3 Code:

//create player
R.instance({_origin: this, _updatable: 1, _saveToXML: 1, _bodyType: "DYNAMIC", _type: "o_nape_player", _sprite: "idle/CharacterIdle", _x: -32, _y: -512});

//R.instance function exposed + showing how the parameters_ get's passed through
class RInstance {
    public static function create(parameters_:Object = null):Dynamic {
        var instance:XxxxObject = null;
        var _type:String = parameters_._type;

        switch (_type) {
            case "o_nape_player": instance =  new O_nape_player(parameters_);
        }
        parameters_._origin.addToArrayObject( instance );

        return instance;
    }
}

//o_nape_player.as
public function XxxxObject(parameters_:Object = null) {
    parameters = parameters_;
}

protected function set parameters(parameters_:Object):void {
    var parameter:String;
    for (parameter in parameters_) {
        this[parameter] = parameters_[parameter];
    }
    parameters_ = null;
}

So as the title says, in Haxe, how would I, set the class's variables, based on a bag of variables that are thrown at the class ready to be unpacked?

The closest I've gotten, but this is not the result I want, as it requires setter functions:

override public function set_parameters(object:Dynamic):Void {
    for (param in Reflect.fields(object)) {
        try {
            Reflect.callMethod(this, Reflect.field(this, "set" + param.charAt(0).toUpperCase() + param.substr(1)), [Reflect.field(object, param)]);
        } catch (e:Dynamic) {
            //....
        }
    }
}

Thank you for your time. Please, I must stress, as I just said, that is not the result I want, I want my Haxe code to line up as best as possible with my AS3 code, my AS3 code does not require setter functions, to set variables that belong to a class.

TL;DR

With all the code posted above, I can simply rephrase the question like so; How can I replicate this as simple as possible in Haxe: this[parameter] = parameters_[parameter];

As3 Append XML Node Alphabetically

I'm just messing around on Flash one last time and I am doing some intricate work with XML.

right now, I dumbed down version of my xml file looks like this.

<dashboard>
      <section grade="4">
               <teacher name="Doe">
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
               </teacher>
               <teacher name="bob">
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
               </teacher>
               <teacher name="Steve">
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
                     <student fname="john" lname ="doe"></student>
               </teacher>
</dashboard>

I want to append a new teacher to the list already in alphabetical order. Right now I have the XML file on my main time line. I first check to see if the section and the teacher already exist. If the section does not exist, I will create a new section. If the section does exist already, than I want the new teacher to be added alphabetically. I am guessing, for the latter, I have to create and add each teacher node to an array. (will that keep it's children along with it?)Then I need to Sort it, and rewrite it back to the file. However I am just confused as to how I keep all the attributes in tact, keep all the students with the teacher, and how I write the nodes to an array.

This is what I have now....it's not much.

function createSectionArray():void
{
      // Checks if the section already exists from a string variable that was checked in a previous frame
      if (MovieClip(this.root).myXML.section.(@grade == sectionGrade).length() > 0)
    {
    // run through all children from that node into array
    for (var d:int = 0; d < MovieClip(this.root).myXML.section.(@grade == sectionGrade).children().length(); d++)
    {
        var node:String = MovieClip(this.root).myXML.section.(@grade == sectionGrade).teacher[d];
        yea I don't know....  I'm at a loss
    }
} else
{
    trace ("There are no other teacher's in this section");
}

}

Thank you for your help!

How to create different file names for every new document in Photoshop?

I have an A4 size document with 6 Photos, while I am trying to cut one photo from the original and create a new document the new file name is created as "Untitled-1".

Since I am using an Action to cut from original and paste it into the new document, every new file is opened with same name as "Untitled-1" and while saving it replaces the existing.

Is there any way to make every new document with sequence number or any different names for each file while create new document in Photoshop?

Or else please suggest if any script is available for the same.

Please find below screenshot for your clear understanding.

thanks in advance.

Full page image

Every new document name

How can I set the scrolling box mc 50px from the bottom

I Have a mc called box.

All I want is when scrolling up I want the bottom of box mc 50px from the bottom of the stage.

Now it's in the middle of the stage.

Here is my code.

var topY:int = stage.stageHeight - box.height;
var botY:int = 0;

box.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
box.addEventListener(MouseEvent.MOUSE_UP, onUp);
var constrainY:Rectangle = new Rectangle(box.x, topY ,0, box.y+ (box.height-stage.stageHeight)  );
var dragxy:String = "";
function onDown(e:MouseEvent):void
{
    dragxy = mouseX + "_" + mouseY;
    e.currentTarget.startDrag(false, constrainY);
}
function onUp(e:MouseEvent):void
{
    e.currentTarget.stopDrag();
}

AS3: TyperError: Error #2007: Parameter hitTestObject myst be non-null

I've been working on this error for a while and I've pretty much exhausted every option other than to post here with the specific code looking for an answer. I've been through past questions with the same error and it hasn't given me much luck, so I would love a quick solution to this issue.

I'm trying to run a code to make the enemy object reset its position every time it connects with the player controlled object (characterMC). Every time I've tried to run this code it's given me the same error. Apologies in advance for messy code, I've just started learning.

Document class code:

package  {

import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.geom.Rectangle;
import player;

public class Memento extends MovieClip {

        //importing required variables
    private var onScreenContent:Array;
    private var playerSkill:int;
    private var myXY:Array;
    private var mySpeed:int;
    private var border:Rectangle;
    private var myMaxItems:int;
    private var numItems:int;
    private var numEnemies:int;
    private var maxEnemies:int;
    private var characterMC:player;
    private var sanity:int;
    private var mementos:int;
    private var score:int;

            //CONSTRUCTOR
        public function Memento() 
        {
            trace("initialising DOS game");
                //simulates a selected skill level  
            playerSkill = 3;
            sanity = 5;
            mementos = 0;
            score = 0;
            onScreenContent = new Array;
            border = new Rectangle(30, 180, 870, 750);
        }

            //code to add character into game at correct position
        private function addCharacter():void 
        {
            trace("Adding the character");
                //set the initial values to character starting pos
            var myXY :Array = [480, 900];
            var mySpeed:int = playerSkill + 6;
                //create and add a new player to screen
            characterMC = new player(myXY, border, mySpeed);
            addChild(characterMC);
            characterMC.focusRect = false;
            stage.focus = characterMC;
        }   //end function addCharacter

        private function addItems():void
        {
            trace("Initialising items");
                //amount of items
            var myMaxItems:int = playerSkill + 1;
                //adding the items one at a time
            for (var numItem:int = 0; numItem < myMaxItems; numItem++)
            {
                var thisItem:collect = new collect(border,playerSkill);
                thisItem.name = "Item";
                    //adding item to stage
                onScreenContent.push(thisItem);
                addChild(thisItem);
            }   //end for statement
        }   //end function addItems

        private function addEnemy():void
        {
            trace ("Adding Enemies");
                //setting initial number of enemies to match game/skill level
            var maxEnemies:int = playerSkill + 1;
                //adding enemies one by one using a loop
            for (var numEnemies:int = 0; numEnemies < maxEnemies; numEnemies++)
            {
                    //creating a new enemy
                var thisEnemy:enemy = new enemy(border,playerSkill,characterMC);
                thisEnemy.name = "Enemy";
                trace ("adding enemies to stage");
                onScreenContent.push(thisEnemy);
                addChild(thisEnemy);
            }
        }
        //function to return from map stage back to main menu
        function exitMap(event:MouseEvent):void
        {
            gotoAndStop(1);
                //removing player, items and enemies from map
            removeChild(characterMC);
        }   //end function exitMap

    }   //end class

}   //end package

enemy class code:

package  {

import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.geom.Rectangle;

public class enemy extends MovieClip{

    private var borderEnemy:Rectangle;
    private var charNum:int;
    private var charSpeed:int;
    private var charDir:int;
    private var offset:int;
    private var characterMC:MovieClip;

        //CONSTRUCTOR FUNCTION
    public function enemy(myBorder:Rectangle, mySkill:int, player:MovieClip) {
        //set values
        trace ("initialising an Enemy");
        mySkill = 3;
        characterMC = player;
        borderEnemy = new Rectangle(50, 180, 840, 750);
            //setting constraing area
        borderEnemy = myBorder;
        offset = 20;
            //nasty type linked to mySkill
        charNum = Math.ceil(Math.random() * (mySkill + 2));
        charSpeed = charNum + 1;
            //what can I hit?
            //eventlistener: starts code when character enters stage
        addEventListener(Event.ADDED_TO_STAGE, initEnemy);
        addEventListener(Event.ENTER_FRAME, checkCollision);
    }   //end function enemy

    private function initEnemy(evt:Event):void
    {
            //displaying the enemy frame (appearence) according to charNum
        gotoAndStop(charNum);
            //setting item positon, linked to function
        setPosition();
            //start movement of enemy, linked to function
        addEventListener(Event.ENTER_FRAME, moveEnemy);
            //remove unneeded listener after initiation
        removeEventListener(Event.ADDED_TO_STAGE,initEnemy);
            //enemy collision event listener, constant
    }   //end function initEnemy

    private function setPosition():void
    {
            //setting enemy positions
        trace ("setting enemy position");
            //code to determine enemy direction
        //charDir =(Math.random() > .5) ? true : false;
        charDir = Math.floor(Math.random() * 2);
        trace ("charDir value is " + charDir);
            //code to determine enemy location (vertically)
        var myRand:int = Math.ceil(Math.random() * 8) * (Math.ceil(Math.random() * 5) + 2);
        if (charDir < 1) {
            trace ("char entering from left");
            //random option 1: character appears from the left
            charDir = 1;
            this.x = borderEnemy.left - offset - myRand;
            this.scaleX = 1;
        } else {
            trace ("char entering from right");
            //random option 2: character appears from the right
            charDir = -1;
            this.x = borderEnemy.right + offset + myRand;
            this.scaleX = -1;
        }
            //set verticle position using myRand
        var myHeight:int = borderEnemy.bottom - borderEnemy.top - offset * 1;
        this.y = Math.ceil(Math.random() * myHeight) + borderEnemy.top * 1;
    }   //end function setPosition
        //function to move enemies

    private function moveEnemy(evt:Event):void
    {
        if (charDir < 1) 
        {
            this.x += -charSpeed - 10;
        } else {
            this.x += charSpeed + 10;
        }
        //reset character as it hits the border
        if(this.x < borderEnemy.left - 40 || this.x > borderEnemy.right + 40)
        {
            setPosition();
        }
    }   //end function moveEnemy

    private function checkCollision(evt:Event):void 
    {
        //detecting if enemy has hit the player character
        if (this.hitTestObject(characterMC)) 
        {
            trace("Hit an enemy");
            setPosition();
        }
    }
}   //end class

} //end package

The error from the output reads

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

repeating over and over as the collision script does its work.

I'd be grateful for any help anyone can provide me. This issue has really been wearing me down the past day and I just want to get it resolved, thanks!

dimanche 23 octobre 2016

hexagon grid drawing issue

I seem to be having a bit of trouble drawing a proper hex grid:

seems ok misaligned

As you can see, the hexagons are just slightly misaligned, though I believe my math is correct (some of which is verfied via http://ift.tt/1456Dli).

My method of drawing is to start at the top left hexagon (first tile in the first row) and draw that row of tiles. Then for the next row, there is a negative X offset and positive Y offset, etc until it reaches the middle row, at which the X offsets increase until 0:

private function drawHexGrid(inputGraphics:Graphics, inputPos:Point, inputGrid:HexGrid, inputTileSize:int):void {

    var rootThree:Number = Math.sqrt(3); // seems like this will be used a lot

    // total number of rows and also size of largest row (in tiles)
    var totalRows:int = (2 * inputGrid.size) - 1;

    // the other useful dimension of a hex tile
    var triSize:Number = rootThree * 0.5 * inputTileSize;

    var topLeft:Point = new Point(-(inputGrid.size - 1) * triSize, -(1.5 * (inputGrid.size - 1) * inputTileSize));
    topLeft.x += inputPos.x;
    topLeft.y += inputPos.y;
    var currentPos:Point = topLeft.clone();

    // step size between each tile and row
    var xStep:Number = rootThree * inputTileSize;
    var yStep:Number = triSize * rootThree;

    var offsetDirection:int = -1;
    var rowLimit:int = inputGrid.size;
    var offsetAmount:int = 0; // offsetAmount goes 1 to n, then back to 0 again, used for calculating thw row offsets

    var mazeTiles:Vector.<Tile> = inputGrid.getTiles();
    var tileCounter:int = 0; // index to cycle through mazeTiles

    for(var rowCount:int = 0; rowCount < totalRows; rowCount++){
        currentPos.x = topLeft.x + (offsetAmount * rootThree / -2 * inputTileSize);

        for(var counter:int = 0; counter < rowLimit; counter++){
            drawHexTile(inputGraphics, currentPos.x, currentPos.y, inputTileSize, mazeTiles[tileCounter++]);
            currentPos.x += xStep;
        }

        currentPos.y += yStep;

        if(rowCount == (inputGrid.size - 1)){
            offsetDirection *= -1;
        }
        rowLimit += offsetDirection * -1;
        offsetAmount -= offsetDirection;

    } // end of for loop
} // end of drawHexGrid()

The actual drawing of each hexagon is in this loop:

private function drawHexTile(inputGraphics:Graphics, inputX:int, inputY:int, inputSize:int, inputTile:Tile):void {
    inputGraphics.lineStyle(0.1, 0, 1);

    var convertToRadians:Number = Math.PI / 180;

    // easier to draw by wall, since need to look up each wall and can set a starting degree without having to worry about the 'end degree'
    // (since the end may not be 360 degrees if the starting degree is in the negatives or a high degree)
    var degrees:int = -150; // starting wall is the top left wall of the hexagon tile
    for(var counter:int = 0; counter < 6; counter++){

        if(inputTile.walls[counter] == true){
            inputGraphics.moveTo(inputX + (Math.cos(degrees * convertToRadians) * inputSize), 
                                    inputY + (Math.sin(degrees * convertToRadians) * inputSize));

            inputGraphics.lineTo(inputX + (Math.cos((degrees + 60) * convertToRadians) * inputSize), 
                                    inputY + (Math.sin((degrees + 60) * convertToRadians) * inputSize));
        }
        degrees += 60;
    }

} // end of drawHexTile() method

At first glance, I think the issue is due to floating point math accuracy, though I'm not sure how to go about fixing/improving this.

Any ideas?

I am aware that my drawing method would end up with many overlapping lines, which is fine for the moment. If it helps, the overall code is meant for a hexagon maze generator, which is working fine and thus can be ignored as it isn't part of the problem.

And if it helps, how I am storing the hexagon tiles is just in one long array, indexed like this:

where n=4

             0       1       2       3
         4       5       6       7       8
     9      10      11      12      13      14   
15      16      17      18      19      20      21
    22      23      24      25      26      27   
        28      29      30      31      32
            33      34      35      36

RegExp how to deal with RegExp When you call the construcor?

I've different results if I use a RegExp pattern and when I use a new RegExp pattern... I'm a noob with RegExp. So

import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.Graphics;
import flash.text.TextField;
import flash.ui.ContextMenu;

    var myString1:String = "Sharsks in the sea";
    var pattern1:RegExp = new RegExp("^\s*|\s*$","gim");
    var pattern2:RegExp = new RegExp("\s*|\s*$","gim");
    var pTest:RegExp = /\s*|\s*$/gim;
    var result1:String = myString1.replace(/^\s*|\s*$/gim,"_");
    var result2:String = myString1.replace(pattern1,"_");
    var result3:String = myString1.replace(/\s*|\s*$/gim,"_");
    var result4:String = myString1.replace(pattern2,"_");
    var result5:String = myString1.replace(pTest,"_");

    trace(result1);
    trace(result2);
    trace(result3);
    trace(result4);
    trace(result5);

    outputs : 
    _Sharsks in the sea_
    _harsks in the sea_
    _S_h_a_r_s_k_s__i_n__t_h_e__s_e_a_
    __h_a_r__k__ _i_n_ _t_h_e_ __e_a_
    _S_h_a_r_s_k_s__i_n__t_h_e__s_e_a_

Can anyone tell me the difference between new operator and a logical RegExp pattern.

I know that is a very stupid question, so pardon me, but I'm confused...

How to get the micro time using Sampler classes in Flash?

I've tried everything to get the microtime in Flash using the sampler class but to no avail. Here is my code so far:

import flash.sampler.Sample;
import flash.sampler.getLexicalScopes;
import flash.sampler.getMemberNames;
import flash.sampler.getSampleCount;
import flash.sampler.getSamples;
import flash.sampler.getSize;
import flash.sampler.startSampling;
import flash.sampler.stopSampling;

private function init():void {

    startSampling();

    var x:String = "Hello world";

    stopSampling();

    var samples:Object = getSamples();
    var sampleCount:int = getSampleCount(); // 0
}

Here is the Sampler and SamplerScript class. It is calling setconst_time to get the time.

I need help quite fast

Guys I am new to Flash professional. I need to make a game before tomorrow.I found a tutorial but I can't understand these codes.Can anyone help me by creating the AS code. Thanks and please guys. Heres' the link.!

samedi 22 octobre 2016

What is an 'action' layer in Adobe Gaming SDK context?

I am using IntelliJ and Adobe Gaming SDK (Adobe Air & AS3) to learn how to write a game. In the tutorial I'm following, the author mentions an 'action layer' in an the main .fla file. This is about mid-way down the page.

I don't have a "main .fla" file, just .as source files. Is there a place for me to put the kind of code to which the author is referring? Here is a snippet:

stop();

//setting vars to step in for turns and special blocks
var S:String = 'START';
var F:String = 'FINISH';
var U:String = 'UP';
var R:String = 'RIGHT';
var D:String = 'DOWN';
var L:String = 'LEFT';

var startDir:String;//the direction the enemies go when they enter
var finDir:String;//the direction the enemies go when they exit

// ...and more

It appears that as some examples have demonstrated, this is where key mapping/binding would also be added for event handlers, etc.

My question is, since I am not using the Flex SDK, and have a pure ActionScript module, where do I put this type of source?

flex mobile - fastest way to load local file?

I'm gonna load local files in Flex mobile environment.

there are so many ways to load local files in Flex mobile.

URLLoader(URLLoaderDataFormat.BINARY), Loader, URLStream, FileStream etc.

so, what will be the fastest way to load local files in Flex mobile? (android)

I'll be waiting nice answer. thanks :)

How do I create dynamically text in a movie clip [AS3]?

I want click on button not text thank you for anyone can help

      btn_start.t1.text = "hello world" // not working

vendredi 21 octobre 2016

Does colorTransform relate to Shape?

I'm trying to create a code where whenever I move my mouse cursor through a shape, it will change colour. I'm stuck at the point where I can only think of adding a new shape on top of the old shape with a new colour. Is there a way to change the colour of the shapes directly instead of creating a new shape and adding a new child every time? I tried using colourTransform but graphics wouldn't allow me to do anything with it in regards to changing the colour of the shapes.

Flash Builder 4.7 (Eclipse) - Settings crash

Everytime I exit Flash Builder 4.7, the next time I open it it tries to load settings but then crashes and generates a log. If I try to open FB again, it loads but all of my projects and tabs are closed. The log tells me it's seems trying to load a UI element, but can't so it clears my previous workspace. Here is the log output file:

!ENTRY org.eclipse.jface 4 0 2016-10-21 14:23:36.917
!MESSAGE The URL "bundleentry://501.fwk104739310/icons/full/dlcl16/refresh.gif" could not be extracted probably due to insufficient permissions or insufficient disk space.
!STACK 0
java.io.IOException: The URL "bundleentry://501.fwk104739310/icons/full/dlcl16/refresh.gif" could not be extracted probably due to insufficient permissions or insufficient disk space.
    at org.eclipse.core.runtime.internal.adaptor.URLConverterImpl.toFileURL(URLConverterImpl.java:40)
    at org.eclipse.core.runtime.FileLocator.toFileURL(FileLocator.java:206)
    at org.eclipse.jface.resource.URLImageDescriptor.getFilePath(URLImageDescriptor.java:137)
    at org.eclipse.jface.resource.URLImageDescriptor.createImage(URLImageDescriptor.java:157)
    at org.eclipse.jface.resource.ImageDescriptor.createResource(ImageDescriptor.java:165)
    at org.eclipse.jface.resource.DeviceResourceManager.allocate(DeviceResourceManager.java:56)
    at org.eclipse.jface.resource.AbstractResourceManager.create(AbstractResourceManager.java:88)
    at org.eclipse.jface.resource.LocalResourceManager.allocate(LocalResourceManager.java:82)
    at org.eclipse.jface.resource.AbstractResourceManager.create(AbstractResourceManager.java:88)
    at org.eclipse.jface.resource.ResourceManager.createImageWithDefault(ResourceManager.java:192)
    at org.eclipse.jface.action.ActionContributionItem.updateImages(ActionContributionItem.java:1044)
    at org.eclipse.jface.action.ActionContributionItem.update(ActionContributionItem.java:783)
    at org.eclipse.jface.action.ActionContributionItem.fill(ActionContributionItem.java:342)
    at org.eclipse.jface.action.ToolBarManager.update(ToolBarManager.java:353)
    at org.eclipse.ui.internal.ViewPane.updateActionBars(ViewPane.java:452)
    at org.eclipse.ui.internal.ViewActionBars.updateActionBars(ViewActionBars.java:59)
    at org.eclipse.search2.internal.ui.SearchView.initializeToolBar(SearchView.java:562)
    at org.eclipse.search2.internal.ui.SearchView.createPartControl(SearchView.java:496)
    at org.eclipse.ui.internal.ViewReference.createPartHelper(ViewReference.java:375)
    at org.eclipse.ui.internal.ViewReference.createPart(ViewReference.java:229)
    at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595)
    at org.eclipse.ui.internal.Perspective.showView(Perspective.java:2245)
    at org.eclipse.ui.internal.WorkbenchPage.busyShowView(WorkbenchPage.java:1145)
    at org.eclipse.ui.internal.WorkbenchPage$20.run(WorkbenchPage.java:3921)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.showView(WorkbenchPage.java:3918)
    at org.eclipse.search2.internal.ui.SearchViewManager.activateSearchView(SearchViewManager.java:101)
    at org.eclipse.search2.internal.ui.InternalSearchUI.runSearchInBackground(InternalSearchUI.java:162)
    at org.eclipse.search.ui.NewSearchUI.runQueryInBackground(NewSearchUI.java:132)
    at org.eclipse.search.ui.NewSearchUI.runQueryInBackground(NewSearchUI.java:105)
    at org.eclipse.search.internal.ui.text.TextSearchPage.performAction(TextSearchPage.java:245)
    at org.eclipse.search.internal.ui.SearchDialog.performAction(SearchDialog.java:476)
    at org.eclipse.search.internal.ui.util.ExtendedDialogWindow.buttonPressed(ExtendedDialogWindow.java:164)
    at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:624)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:240)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4128)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1457)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1480)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1465)
    at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1270)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3974)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3613)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
    at org.eclipse.jface.window.Window.open(Window.java:801)
    at org.eclipse.search.internal.ui.OpenSearchDialogAction.run(OpenSearchDialogAction.java:54)
    at org.eclipse.search.internal.ui.OpenSearchDialogAction.run(OpenSearchDialogAction.java:45)
    at org.eclipse.search.internal.ui.OpenSearchDialogPageAction.run(OpenSearchDialogPageAction.java:79)
    at org.eclipse.ui.internal.PluginAction.runWithEvent(PluginAction.java:251)
    at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:229)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
    at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
    at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:452)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4128)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1457)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1480)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1465)
    at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1270)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3974)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3613)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2696)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2660)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2494)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:674)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:667)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at com.adobe.flexbuilder.standalone.FlashBuilderApplication.start(FlashBuilderApplication.java:79)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1410)

Somtimes it also complains about these file paths, among others:
bundleentry://501.fwk104739310/icons/full/dlcl16/stop.gif
bundleentry://501.fwk104739310/icons/full/dlcl16/pin_view.gif
bundleentry://501.fwk104739310/icons/full/dlcl16/search_history.gif
Any guidance is appreciated.

Heyzap Fyber integration Adobe Air

I'm trying to integrate the Heyzap SDK 10 to my AdobeAIR iOS project with no luck. I could start the services using the SDK 9 but with the new SDK I just get a "Fyber Version 8.5.2 - Waiting for SDK to start" when I try to open the mediation test suit.

I followed the documentation step by step and most likely implemented everything as supposed to be. Do you have any clue on this issue?

I'm using Adobe Flash Professional CS6 AIR 23.0.0.274 Latest Heyzap SDK 10 Starling

Thanks, Gionathan

Cursor movement too fast for code to read

I have created a MOUSE_MOVE MouseEvent and a code to draw circles while I move the mouse cursor. The problem is, it doesn't draw out every single circle if I move the mouse too fast. After I move the mouse cursor in a line with moderate speed

Here are the codes I have for the MOUSE_MOVE event.

stage.addEventListener(MouseEvent.MOUSE_MOVE, mCursor);

public function mCursor(e:MouseEvent):void
{

    var cursor:Shape = new Shape();

    cursor.graphics.beginFill(1, 1);
    cursor.graphics.drawCircle(e.stageX, e.stageY, 10);
    cursor.graphics.endFill();
    addChild(cursor);
}

Would there be an arithmetic equation or physics formula to have it add every single circle such that it can draw a straight line without the blanks in between?

Save and Load variables to xml or txt in as3

I need to save a few variables to another file on the server in the same directory. Ideally, TXT or XML, but can not find some simple functional process usually only retrieval of XML. How to do it as simply as possible, I need to save 2 propměnné numeric and text strings as 2 scores. Currently it got solved by SharedObject.getLocal, but I need it just for online use. How to do it pleas

Enabling async rendering in flash

Regarding bug in firefox: http://ift.tt/2dhK5rt

Flash is not working properly, strange stuff happend(Mouse events are dispatching with time lag, they are dispatching by themselves, etc.). Solution is by link from firefox: enable async rendering.

There is also a separate functional regression caused by Adobe in bug 1301486 which would be fixed by enabling async rendering.

Is something like that possible to do in Flash, in AS3 code ? When we set this in option in firefox(dom.ipc.plugins.asyncdrawing.enabled) it solve the problem.

Thank you in advance for any answer Egid

jeudi 20 octobre 2016

Adobe Flex Declaration Tag

Hello I'm using Adobe Builder 4,6 I have a Flex project. I have a code as you see that,

This is Code

and I have and error like this.

What can I do against that error I tried delete Declaration tag but it couldn't solve this.

as3 move object back and forth

I am working on a 2d project for iPad where a ball moves back and forth. When it hits the border it had to rotate a bit and roll back in another direction and leaving a child behind that follows its own path.

ball_mc.addEventListener(Event.ENTER_FRAME, moveBall);

function moveBall(e:Event):void {

ball_mc.rotation += 1;
if (ball_mc.x < (stage.stageWidth - 100)) {
    //trace('move forward');
    ball_mc.x += 2;

} else {
    while(ball_mc.x > 100){
    //  trace('move backward');
        ball_mc.x += -2;
    }
}

}

How to resize an image on drag?

I have a couple of images I want to use in a drag and drop game. I've got this working through the actionscript code snippets but I also need these images to be able to resize by dragging an arrow or something similar at the bottom corner. I can either get the dragging working by not including the resize code and vice versa.

this.addEventListener(MouseEvent.MOUSE_MOVE, resize);
this.addEventListener(MouseEvent.MOUSE_UP, stopDragging, true);
this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging, true);
function startDragging(E:MouseEvent):void {
    resize1.startDrag();
}

function stopDragging(E:MouseEvent):void {
    resize1.stopDrag();
}
function resize(E:MouseEvent):void {
    item1_mc.width = resize1.x - item1_mc.x;
    item1_mc.height = resize1.y - item1_mc.y;
}

Does anyone have any idea how to fix this? I know my image resize code is primitive at the moment but that can be changed to scaling soon enough.

Publish Air App error timestamp

I have an error when I publish an air app using flash cs6 I know that timestamp website down and I update java to 1.8 but I still Have the same error any idea ??

mercredi 19 octobre 2016

Youtube video on AIR iOS app isn't displayed anymore with AIR 23

I'm updating my iOS AIR app, and when I compile my IPA file using AIR 23, Youtube videos refuse to show up within my app.

When I compile with AIR 20, everything goes back to normal, and youtube videos run normally on an iPhone.

I'm using the "StageWebView + iframe" method to display the video within the AIR app.

The code I use is written below, is there anything I need to change to make it compatible with AIR V23? Thanks a lot!!!!

           webViewYoutube = new StageWebView();

           webViewYoutube.stage=stage;



           var htmlString:String = "<!DOCTYPE HTML>" +

                    "<html><body bgcolor="+ "Black" + "><script>" +

                    "var tag = document.createElement('script');"+

                    "tag.src = \"http://www.youtube.com/player_api\";"+

                    "var firstScriptTag = document.getElementsByTagName('script')[0];"+

                    "firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);"+

                    "var player;"+           

                    "function onYouTubeIframeAPIReady() {"+

                        "player = new YT.Player('player', {"+            

                          "events: {"+

                            "'onReady': onPlayerReady,"+

                          "}"+

                        "});"+

                    "}"+

                    "function onPlayerReady(event) {"+

                        "event.target.playVideo();"+

                    "}"+

                    "</script>"+

                    "<iframe id=\"player\" type=\"text/html\"width=\"100%\" height=\"100%\"src=\"http://www.youtube.com/embed/XXXXXXXXXX?autohide=1&controls=1&modestbranding=0&rel=0&showinfo=0\" frameborder=\"0\"></iframe>" +

                    "</body></html>";



           webViewYoutube.loadString(htmlString);

           swvHeight = stage.stageHeight;

           webViewYoutube.viewPort = new Rectangle(0, 0, this.stage.stageWidth, swvHeight);

How can I remove this child image Flash / AS3

Following tutorials I managed to cobble the following together that imports an image from an external XML file.

But how do I remove it?

I've read up on removeChild but it looks like it needs to have a ref passed to it and I'm not sure what that ref is. I've tried a few things that I thought it might be, including (image) but all of them throw up Access of undefined property errors.

This is the code I'm using to import :

var imgrequest:URLRequest = new URLRequest(artwork);
var loader:Loader = new Loader();   

    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_loadComplete);

    function on_loadComplete(e:Event):void {
        var image:DisplayObject = loader.content;       
            image.x = 0;
            image.y = 4;
            image.width = 150;
            image.height = 150;
        addChild(image);      
        Bitmap(image).smoothing = true;
    }
    loader.load(imgrequest);

What do I need to do to remove it?

Select "youngest" child in AS3?

I'm just making a solitaire game to try to better learn OOP. I have a Card class and a CardHome class. Each Card contains a CardHome which can hold a card, and so on. Thus, moving a card will move all the cards contained in it. The problem is that my mouse event is detecting the parent of all the cards. So what I think I need is a way to say "run this mouse event only for the youngest child of the target". Any way to do that?

private function pressCard(me:MouseEvent):void{
        trace(me.target);
        trace(me.target.parent);
        trace(me.target.parent.parent);
        trace(me.target._number,me.target._suit);
        var c:Object = me.target as Card;
        // place card in center of container x wise
        c.x = 0;
        // and down 5
        c.y = 5;

        // bring drag container up to front z order
        addChild(c as Card);

        // begin dragging drag container
        c.startDrag(true);

        // hide mouse
        Mouse.hide();

        // add listener to this card for mouse up
        c.addEventListener(MouseEvent.MOUSE_UP,dropCard);
    }

    private function dropCard(me:MouseEvent):void{
        var c:Object = me.target as Card;

        // release drag container
        c.stopDrag();

        // remove mouse up listener from card
        c.removeEventListener(MouseEvent.MOUSE_UP,dropCard);
        Mouse.show();


        // check for colision with a card that has a matching holder
        for (var i:int = 0; i < deckArray.length; i++){
            if (c.hitTestObject(deckArray[i]) && c != deckArray[i]){
                trace("hit",deckArray[i]._containerOwned._occupied,deckArray[i]._flippable);
                if (deckArray[i]._number == c._number + 1 && deckArray[i]._flippable == false && deckArray[i]._suit != c._suit && deckArray[i]._containerOwned._occupied == false){ 
                    //c.alpha = .9;
                    c._containedIn.parent._containerOwned._occupied = false;
                    makeFlippable(c._containedIn.parent);
                    deckArray[i]._containerOwned.addChild(c as Card);
                    c._containedIn = c.parent;                      
                    c.x = 0;
                    c.y = 0;
                    break;
                } 
            }
        }

        // add selected card back to home spot
        c._containedIn.addChild(c);
        c.x = 0;
        c.y = 0;
    }

    private function mOver(me:MouseEvent):void{
        trace(me.target._number);
        trace(getHighestZ());
    }

    private function getHighestZ():Card{
        var highestZ:int = 0;
        var c:Card;
        for (var i:int = 0; i < deckArray.length; i++){
            if (deckArray[i].hitTestPoint(stage.mouseX,stage.mouseY) && deckArray[i].getChildIndex() > highestZ){
                c = deckArray[i];
                highestZ = deckArray[i].getChildIndex();
            }
        }
        return c;
    }

enter image description here

Each card is a child of a container in the card above it. I want to be able to select a card and drag it (and its children). The problem is that when I click card B, it selects card E. So what I need is to select the youngest child in the mouse event, and NOT its parent. Any way to control that?

I know I can do mouseChildren true or false. That's fine. It has to be set to true for all of the cards so that I can select them independent of their parent card. Do I need to do something with bubbling my event? That's something I've never understood.