vendredi 30 octobre 2015

If condition explanation AS3

I found this code online. But I'm not completely sure what it means. It's to create a bouncing ball. Im just not sure whats saying in this if condition.

is it about the speed of the object or the where it's going to appear in the stage? Could u please add a //comment for a brief explanation. Thank you in advance!

        if ( this.x >= nStageWidth - 10 )
        {
            this.x = nStageWidth - 10;
            nSpeedX *= -1;
        }
        else if ( this.x <= 10 )
        {
            this.x = 10;
            nSpeedX *= -1;
        }

        if ( this.y >= nStageHeight - 10 )
        {
            this.y = nStageHeight - 10;
            nSpeedY *= -1;
        }
        else if ( this.y <= 10 )
        {
            this.y = 10;
            nSpeedY *= -1;
        }

I'm getting an Incompatible pointer types warning

I'm trying to create an extension for an AIR application and have been following documentation on Adobe's website and some other examples and everything looks correct but I don't know enough about Objective C to know why I'm getting this warning.

#import "FlashRuntimeExtensions.h"

@import Contacts;
@import UIKit;

CNAuthorizationStatus contactStatus;
CNContactStore * contactStore;
CNContactFetchRequest * request;
NSMutableArray * contacts;
NSArray * fullContactList;

FREObject HasContactListAccess(FREContext ctx, void* funcData, uint32_t argc) {
    uint32_t statusResult = true;

    if(contactStatus == CNAuthorizationStatusDenied){
        statusResult = false;
    }

    FREObject returnBoolean = nil;
    FRENewObjectFromBool(statusResult,&returnBoolean);

    return returnBoolean;
}

FREObject GetAllContacts(FREContext ctx, void* funcData, uint32_t argc){
    contactStore = [[CNContactStore alloc] init];
    [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        contacts = [NSMutableArray array];
        NSError * fetchError;
        request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

        BOOL success = [contactStore enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact * _Nonnull contact, BOOL * stop) {
            [contacts addObject:contact];
        }];

        if(!success) {
            NSLog(@"error = %@", fetchError);
        }

        fullContactList = [contacts copy];
    }];



    FREObject contactsObject = NULL;
    FRENewObject((const uint8_t*)"Array", 0, NULL, &contactsObject, nil);

    return contactsObject;
}

void AIRContextInitializer(void* extData, const uint8_t* ctxType, FREContext ctx, uint32_t* numFunctionsToSet, const FRENamedFunction** functionsToSet){
    contactStore = [[CNContactStore alloc] init];

    *numFunctionsToSet = 2;
    FRENamedFunction* func = (FRENamedFunction*)malloc(sizeof(FRENamedFunction) * *numFunctionsToSet);

    func[0].name = (const uint8_t*)"hasContactListAccess";
    func[0].functionData = NULL;
    func[0].function = &HasContactListAccess;

    func[1].name = (const uint8_t*)"getAllContacts";
    func[1].functionData = NULL;
    func[1].function = &GetAllContacts;

    *functionsToSet = func;
}

void AIRContextFinalizer(FREContext ctx) {
    return;
}

void AIRExtensionInitializer(void** extDataToSet, FREContextInitializer* ctxInitializerToSet, FREContextFinalizer* ctxFinalizerToSet) {
    *extDataToSet = NULL;
    *ctxInitializerToSet = &AIRContextInitializer;
}

The warnings are showing on lines 59 and 63:

func[0].function = &HasContactListAccess;
func[1].function = &GetAllContacts;

Creating a custom class and linking to Main class

I pretty much just want to create a separate class for my lists of words instead of cluttering my main class. Everything works fine if the array is in my Main Class. My problem is Im not sure how Im suppose to create the Array custom class and then link it to the main class. Here's what I have so far

package  {

public class RandomText  {


    public function RandomText() {
        var randomKill:Array = new Array("Goats",
                      "Bananas",
                      "Cows",
                      "a Printer",
                      "Pineapples",
                      "a Toothbrush")


    }

}

}

This is the one in my Main Class, but I'm not sure how I can link the Array class to this one. I kept getting an error saying Property length not found on RandomText and there is no default value at Main/moveCell(). Thanks a lot in advance!

 for (var i:int = 0; i < group.length; i++)
             {
                 var cell:Cell = Cell(group[i]);
                 if (cell.hitTestObject(island))
                 {
                     cell.parent.removeChild(cell);
                     group.splice(i,1);

                     score++;
                     //trace("hit me");

                     var randomText = new RandomText();
                      randomIndex =  Math.random () * randomText.length;
                     txtWordDisplay.text = "Killed by " + randomText[randomIndex]

                 }


             }

Iterating through data structure

I'm kinda wracking my brain on how to iterate through my data object. I've created a recursive function to iterate through XML elements and essentially output the same structure as an object, using the attribute in the element as the key, which holds it's own object. The object, conceptually, looks something like this. It's sort of a Tree, but I'm not using flex Trees, just as3.

enter image description here

The thing I want to get across is that each "branch" has any number of children, so I can't hard code the depth of each branch.

What I'm trying to accomplish

Each node in my data structure is a folder name, and I need to append all of the children into a single string and store that. To generate an "asset", i need a string from each of these initial nodes (in the example picture, they'd be 1, 2, 4, 5, 6, and 17). So, I need to iterate through each branch and return a different set than previously, such that every possible asset combination is found.

Conceptually, I know that I need to grab the "1st index" of each branch, output all of those strings into an asset, and then move the first branch up an "index" until it reaches it's limit, which triggers the next branch to move its "index". But, how I actually do that is a bit of a mystery to me.

Do I need to restructure my data tree into an array that can be referenced by index, or is there some simpler way of iterating through every possible combination that I am missing.

I'm using actionscript 3, but I'm not specifically looking for a code example, just pseudo-code is fine.

Generating Random text on Collision AS3

I would like to generate some random words when an object hits another one.

I've tried it but only one word comes up and never changes again.

Also would it be better if I make a new class for the random texts or is including it in the Main class good enough? Thanks!

Here's my current code:

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



public class Main extends MovieClip {

    public var cell:Cell;
    public var group:Array;
    public var gameTimer:Timer;
    public var score:int = 0;
    var array:Array = new Array ("Apples",
                                 "Bananas",
                                 "Grapes",
                                 "Oranges",
                                 "Pineapples"); //create an array of possible strings
    var randomIndex:int =  Math.random () * array.length;
    //public var randomTxt:String;





    public function Main() {

        group = new Array();


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

    private function createCell(_x:Number = 0, _y:Number = 0):void {
        var cell:Cell = new Cell(_x, _y);
        group.push(cell);
        addChild(cell);
    }


     function moveCell (timerEvent:TimerEvent):void {

         if (Math.random() < 0.01) {
             var randomX:Number = Math.random()*800;
             var randomY:Number =  Math.random()*600;
             createCell(randomX, randomY);
         }


         for (var i:int = 0; i < group.length; i++)
         {
             var cell:Cell = Cell(group[i]);
             if (cell.hitTestObject(island))
             {
                 cell.parent.removeChild(cell);
                 group.splice(i,1);
                 score++;
                 txtWordDisplay.text = "Killed by" + array [randomIndex];


             }




         }

    scoreOutPut.text = score.toString();



    }


}

}

Can AS3 non-static constants be assigned?

I'd like a constant instance variable in my class. The following throws an error in the constructior (of course, since I'm assigning to a constant):

public class Rotation {
    public const angle:Number;
    public function Rotation( angle:Number ) {
        this.angle = angle;
    }
}

I assume there is some solution, since it is possible to create non-static constant members.

AS3 Flash i-pad orientation

So I am making a flash app for i-pad and having serious problems with the orientation, I have looked around for sometime but no one elses answers appear to be helping.

I want my app to always be landscape, which is currently working, however when the i-pad is upside down the keyboard comes down the top and the screen goes under the keyboard, leaving the keyboard on the top of the screen over the screen, with a big white space where the screen should be.

Right now I have the following code.

In my xml document

    <aspectRatio>landscape</aspectRatio>
    <autoOrients>false</autoOrients>

And in my main.as

    public class Main extends Sprite 
{
    private var _mainContent:MainContent;
    public function Main() 
    {

        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;
        stage.addEventListener(Event.DEACTIVATE, deactivate);

        // touch or gesture?
        Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

        // Entry point
        _mainContent = new MainContent();
        addChild(_mainContent);
        switch ( stage.deviceOrientation ) 
{ 
    case StageOrientation.DEFAULT: 
        trace("default2");
        stage.setOrientation( StageOrientation.DEFAULT ); 
        break; 
    case StageOrientation.ROTATED_RIGHT: 
        trace("right2");
        stage.setOrientation( StageOrientation.ROTATED_LEFT ); 
        break; 
    case StageOrientation.ROTATED_LEFT: 
        trace("left2");
        stage.setOrientation( StageOrientation.UPSIDE_DOWN ); 
        break; 
    case StageOrientation.UPSIDE_DOWN: 
        trace("down2");
        stage.setOrientation( StageOrientation.UPSIDE_DOWN ); 
        break; 
    default: 
        //No change              
} 

    }

Currently I am getting the trace "left2" however any changes to that part of the switch statement has zero effect.

Any help would be gratefully appreciated. Thanks so much

Removing an Object when it hits another object AS3

Beginner here. I have a symbol on the timeline with an instance name of 'island', so basically I want to remove the cells that hits the 'island'

if (cell.hitTestObject (island)) {

             if(stage.contains(cell))
             removeChild (cell);
         }

I tried this one under the moveCell function but it only removes one cell instead of every cell that hits the island. Thanks everyone!

Here's my code so far:

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

    public class Main extends MovieClip {

        public var cell:Cell;
        public var group:Array;
        public var gameTimer:Timer;


        public function Main() {

            cell = new Cell (400, -15);
            addChild (cell);

            group = new Array();
            var newCell = new Cell (100, -15);
            group.push ( newCell);
            addChild(newCell);


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

        public function moveCell (timerEvent:TimerEvent):void {

             if (Math.random() < 0.01) {
             var randomX:Number = Math.random() * 700;
             var newCell:Cell = new Cell (randomX, -15);
             group.push (newCell);
             addChild(newCell);
             }


        }

    }

}`

drag and drop object tu multiple target with score

This is how my current project work :

One drop target each

  • The result will be display under the original position when ALL objects has been place on their targets
  • Each object currently can be drop to one target
  • Wrong drop target will trigger a fail sound while the object will back to it's original position

The codes are :

stop();

Mouse.show();

page1_btn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
page2_btn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene2);

// Drag And Drop

var objectoriginalX:Number;
var objectoriginalY:Number;

var req5:URLRequest = new URLRequest("good2.mp3");
var good2:Sound = new Sound();
good2.load(req5);

var req6:URLRequest = new URLRequest("wrong.mp3");
var wrong:Sound = new Sound();
wrong.load(req6);

var req7:URLRequest = new URLRequest("good3.mp3");
var good3:Sound = new Sound();
good3.load(req7);

match1_mc.buttonMode = true;
match1_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
match1_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);

match2_mc.buttonMode = true;
match2_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
match2_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);

match3_mc.buttonMode = true;
match3_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
match3_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);

////////////

function pickupObject(event:MouseEvent):void {
event.target.startDrag(true);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
}
function dropObject(event:MouseEvent):void {
event.target.stopDrag();
var matchingTargetName:String = "target" + event.target.name;
var matchingTarget:DisplayObject = getChildByName(matchingTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == matchingTarget){
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
event.target.buttonMode = false;
event.target.x = matchingTarget.x;
event.target.y = matchingTarget.y;
    good2.play();

} else {
event.target.x = objectoriginalX;
event.target.y = objectoriginalY;
    wrong.play();
}

if (
    match1_mc.x == targetmatch1_mc.x &&
    match2_mc.x == targetmatch2_mc.x &&
    match3_mc.x == targetmatch3_mc.x
    ) 

{
    response2_mc.gotoAndStop(2);
    good3.play();
    }
}

what I'm trying to do :

Each object with 3 targets

  • I will remove the sound effect of dropping objects to right/wrong targets
  • I will add a "check" button under the objects which only appears when ALL objects has been dropped to ANY targets.
  • If the objects meets wrong targets, clicking on the "check" button will make ALL the dropped objects back to their initial position and the button will disappear
  • If the objects are correctly place on their targets, clicking the "check" button will trigger a win sound effect or some wording

these codes will be added to the "check" button:

if (
        match1_mc.x == targetmatch1_mc.x &&
        match2_mc.x == targetmatch2_mc.x &&
        match3_mc.x == targetmatch3_mc.x
        ) 

    {
        response2_mc.gotoAndStop(2);
        good3.play();
        }

If possible i would like to have someone help me with :

  • If the objects were dropped on either correct/wrong targets it can be replace by new one and the old one will kick back to it's initial position
  • Dropped object on a target can be move to other targets OR when click on the dropped object, it will go back to the original position

Side note : "good2.mp3" and "good3.mp3" are different sound effect. I'm still a beginner, simple code will be great, complex codes is challenging but i will appreciate it

jeudi 29 octobre 2015

Removing an Object when it hits another object AS3

Beginner here. I have a symbol on the timeline with an instance name of 'island', so basically I want to remove the cells that hits the 'island'

if (cell.hitTestObject (island)) {

             if(stage.contains(cell))
             removeChild (cell);
         }

I tried this one under the moveCell function but it only removes one cell instead of every cell that hits the island. Thanks everyone!

Here's my code so far:

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

    public class Main extends MovieClip {

        public var cell:Cell;
        public var group:Array;
        public var gameTimer:Timer;


        public function Main() {

            cell = new Cell (400, -15);
            addChild (cell);

            group = new Array();
            var newCell = new Cell (100, -15);
            group.push ( newCell);
            addChild(newCell);


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

        public function moveCell (timerEvent:TimerEvent):void {

             if (Math.random() < 0.01) {
             var randomX:Number = Math.random() * 700;
             var newCell:Cell = new Cell (randomX, -15);
             group.push (newCell);
             addChild(newCell);
             }


        }

    }

}`

Adobe Flash CS5.5 keep not responding

I am doing project by using adobe flash cs5.5 As we're doing our work, more images, sounds etc were imported into the library. And the size of file is getting bigger. But, the thing that bug me a lot is, when i was doing my work, adobe flash suddenly appears "not responding" andfreeze. So i need to wait for few secs or minutes to let it settle down before continuing my work. Anyone know why it keep happen and any possible solution to overcome this?

Thank you.

How do I serialize Vector.

http://ift.tt/1lrCrfX I followed this to the T, yet I'm running into issues. I'm trying to save a bunch of icons. They have a custom class "Iconn" and are stored in a Vector.<Iconn> for future use. Once the user adds a new icon, I open up a filestream and use it to write the entire vector.

        public function addShortcut(f:File):void
    {
        //Display on side
        icons.reverse(); //Add to the front so it displays on the top.
        icons.push(new Iconn(f)); //Use 16x16 bitmap

        addChild(icons[icons.length - 1]);
        icons.reverse();

        //Save object
        fs = new FileStream();
        fs.open(shortcuts, FileMode.WRITE);
        fs.writeObject(icons);
        fs.close();

        reorder(); //Reorganizes the icons on the screen.
    }

This works all and well with no errors, but when I try to re-launch the application with some icons saved, the vector doesn't even exist.

    icons = new Vector.<Iconn>();
    if (shortcuts.exists)
    {
        trace("Shortcuts exist..adding");
        fs = new FileStream();
        fs.open(shortcuts, FileMode.READ);
        icons = fs.readObject() as Vector.<Iconn>;
        fs.close();
        trace("icons = " + icons); //TypeError: Error #1009: Cannot access a property or method of a null object reference.
        trace("icons length  = " + icons.length); //TypeError: Error #1009: Cannot access a property or method of a null object reference.
    }

I tried adding registerClassAlias("Vector.<Iconn>", Vector.<Iconn>);, but then I get a compiler error 1067: Implicit coercion of a value of type __AS3__.vec:Vector.<Iconn> to an unrelated type Class.

Adobe Flash Builder Flex Video Player - Full screen on init

I have a created a flex application with a video player. The application goes full screen. Now I am trying to make the video go on full screen on inital launch.

I have tried to google how to do this, but came up with nothing. Here is my app code:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ift.tt/rYUnH9" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       creationComplete="myVid.play();"
                       applicationComplete="init()"
                       showStatusBar="false"
                       xmlns:media="org.osmf.media.*">

    <s:VGroup>
        <s:VideoDisplay id="myVid" 
                        source="augusta.mp4"
                        autoPlay="true"
                        volume="0"
                        loop="true"
                        width="100%"
                        height="100%"
                        />
    </s:VGroup>

    <fx:Script> 
        <![CDATA[
            private function init():void  
            {
                stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
            } 
        ]]> 
    </fx:Script>

</s:WindowedApplication>

How to smoothly scroll content in an AIR Android Application?

I have written a small class to be used to scroll content on mobile devices. The class works fine but the scrolling doesn't feel smooth. Here is the class:

package  {
import flash.display.Sprite;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import flash.geom.Rectangle;
import com.greensock.TweenMax;
import com.greensock.easing.*;
import flash.utils.setTimeout;

public class FlickScroll extends Sprite {

    private var currentY:Number;
    private var lastY:Number;
    private var vy:Number;
    public var clickable:Boolean = true;
    private var dragging:Boolean = false;
    private var firstY:Number;
    private var secondY:Number;
    private var content:InteractiveObject;
    private var masker:InteractiveObject;
    private var topBounds:Number;
    private var bottomBounds:Number;
    private var Offset:Number;
    public var friction:Number = .90;
    public var flickable:Boolean = false;
    public var scrollVelocity:Number;

    public function FlickScroll(Masker:InteractiveObject, Content:InteractiveObject, TopBounds:Number, BottomBounds:Number) {
        masker = Masker;
        content = Content;
        topBounds = TopBounds;
        bottomBounds = BottomBounds;

        this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
    }
    private function onAddedToStage(evt:Event):void
    {
        init();
        this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
        addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);

        content.mask = masker;
        content.cacheAsBitmap = true;
    }
    private function init():void
    {
        currentY = content.y;
        lastY = content.y;
        vy = 0;
        scrollVelocity = 2;
        content.addEventListener(MouseEvent.MOUSE_DOWN, onContentDown, false, 0, true);
    }
    private function onContentDown(evt:MouseEvent):void
    {

        firstY = content.y;
        Offset = content.mouseY;
        trace(mouseY, Offset, mouseY - Offset);

        content.addEventListener(MouseEvent.MOUSE_MOVE, onContentMove, false, 0, true);
        stage.addEventListener(MouseEvent.MOUSE_UP, onContentUp, false, 0, true);
    }
    private function onContentMove(evt:MouseEvent):void
    {

        dragging = true;
        clickable = false;
        content.y = mouseY - Offset;


        if(content.y > topBounds + 200)
        {
            content.y = topBounds + 200;
        }
        else if(content.y < bottomBounds - 200)
        {
            content.y = bottomBounds - 200;
        }



        trace("ContentY: ", content.y, "Bottom Bounds: ", bottomBounds, "Top Bounds: ", topBounds);

        evt.updateAfterEvent();
    }
    private function onContentUp(evt:MouseEvent):void
    {
        secondY = content.y;
        var dy:Number = secondY - firstY;

        if(dy < 20 && dy > -20)
        {
            clickable = true;
        }

        if(content.y > this.topBounds)
        {
            TweenMax.to(content, .4, {y:topBounds, ease:Expo.easeOut});
        }
        else if( content.y < this.bottomBounds)
        {
            TweenMax.to(content, .4, {y:bottomBounds, ease:Expo.easeOut});
        }
        else
        {
            dragging = false;
        }
        //setTimeout(setDraggingFalse, 400);


        content.removeEventListener(MouseEvent.MOUSE_MOVE, onContentMove);
        content.removeEventListener(MouseEvent.MOUSE_UP, onContentUp);
    }
    private function onLoop(evt:Event):void
    {
        if(this.flickable)
        {

            if(dragging)
            {
                lastY = currentY;
                currentY = mouseY;
                vy = (currentY - lastY)/scrollVelocity;
            }
            else
            {
                content.y += vy;
                vy *= friction;
            }
        }

        if(!dragging)
        {
            if(content.y > topBounds)
            {
                content.y = topBounds;
            }
            else if(content.y < bottomBounds)
            {
                content.y = bottomBounds;
            }
        }
    }
    public function updateBounds(top:Number, bottom:Number):void
    {
        bottomBounds = bottom;
        topBounds = top;
    }

    private function setDraggingFalse():void
    {
        dragging = false;
    }

}

}

Sorry for the code being really messy. What steps can I take to make the scrolling feel more smooth? Any help is greatly appreciated.

TypeError: Error #1010: A term is undefined and has no properties. at MineAssign/NukesExplode()

I'm having a problem with this function, "NukesExplode". When a nuke is clicked it's suppose to be removed and replaced by a element from the explodeArray. Instead, when I click it I recieve an output error (the title) and it just disapears.

package {
import flash.display.MovieClip;//allows custom images to be used
import flash.text.TextField;//allows textfields to be used
import flash.events.MouseEvent;//allows buttons and other mouse events to be used
import flash.utils.Timer;//allows timers to be used
import flash.events.TimerEvent;//allows timers to interact with other variables and custom events
import flash.display.Sprite; //allows listener events to take place
import flash.events.Event; //allows events to be invoked and take place
import flash.media.Sound;//allows sound to be used and played
import flash.net.URLRequest;//allows the playing of sounds from the library
public class MineAssign extends MovieClip {//class

    public function MineAssign(){//constructor
        TitleScreen();
    }//End of Constructor

    public function TitleScreen(){//adds a Title Screen
        var tsBackground:tsBack= new tsBack();
        tsBackground.x= -22
        tsBackground.width=650
        tsBackground.height=450
        addChild(tsBackground);

        var mainTheme:tsTheme = new tsTheme(); 
        mainTheme.addEventListener(Event.COMPLETE, CompleteHandler); 
        function CompleteHandler(event:TimerEvent){
        }
        mainTheme.play();

        var counter = 0;
        var myTimer:Timer = new Timer(5000);
        myTimer.addEventListener(TimerEvent.TIMER, TimerFunction)
        function TimerFunction(event:TimerEvent){
            counter++
            removeChild(tsBackground);
            AddStuff();

            myTimer.stop();
        }
        myTimer.start();

    }//end of TitleScreen

    public function AddStuff(){//adds the game

        var mapBack:Map = new Map();
        mapBack.width= 550
        mapBack.height= 400
        mapBack.x= 25
        addChild(mapBack);

        var gameLogo:Logo = new Logo();
        gameLogo.x=25
        gameLogo.y=0
        addChild(gameLogo);

        var subLogo:SubLogo = new SubLogo();
        subLogo.y=45
        subLogo.x=25
        addChild(subLogo);

        var inputFieldOne:TextField= new TextField
        inputFieldOne.y= 400
        inputFieldOne.x= 25
        inputFieldOne.width= 150
        inputFieldOne.text= "Number of Nukes:"
        inputFieldOne.height= 25
        inputFieldOne.border= true
        inputFieldOne.restrict= "0-9"
        addChild(inputFieldOne)

        var inputFieldOneTwo:TextField= new TextField
        inputFieldOneTwo.y= 400
        inputFieldOneTwo.x= 120
        inputFieldOneTwo.width= 50
        inputFieldOneTwo.height= 25
        inputFieldOneTwo.type= "input"
        inputFieldOneTwo.restrict= "0-9"
        inputFieldOneTwo.maxChars=  2
        addChild(inputFieldOneTwo)

        var inputFieldTwo:TextField= new TextField
        inputFieldTwo.y= 425
        inputFieldTwo.x= 25
        inputFieldTwo.width= 150
        inputFieldTwo.height= 23
        inputFieldTwo.border= true
        inputFieldTwo.text= "Click me to drop some nukes!"
        addChild(inputFieldTwo)

        inputFieldTwo.addEventListener(MouseEvent.CLICK, ClickButton2); 
        function ClickButton2(event:MouseEvent) {
            DropNukes(inputFieldOneTwo);
        }

    }//end of AddStuff

    public var theNukes:Array= new Array();
    public var textnum:Number;
    public var explodeArray:Array= new Array();

    public function DropNukes(inputFieldOneTwo){//function that deals with the myNuke array

        textnum= Number(inputFieldOneTwo.text);

        for(var i:int; i < textnum; i++){
            theNukes.push(new myNuke());
            theNukes[i].addEventListener(MouseEvent.CLICK, NukesExplode);
            theNukes[i].x= Math.random()*370+50;
            theNukes[i].y= Math.random()*370-50;
            theNukes[i].rotation= Math.random()*360
            addChild(theNukes[i]);
        }
    }//end of DropNukes

    public function NukesExplode(event:MouseEvent){//function that makes the nukes explode when clicked and calculates the distances to the closest mine

        var clicked:int = theNukes.indexOf(event.currentTarget)
        removeChild(theNukes[clicked]);
        theNukes.splice(clicked, 1);

        for(var i:int; i < textnum; i++){
            theNukes.push(new blownUp());
            explodeArray[i].height= 70;
            explodeArray[i].width= 70;

            if(event.currentTarget == theNukes[i]){//If a nuke is clicked, remove it and replace it with the explode array
                theNukes.splice(i, 0);
                removeChild(theNukes[i]);
                addChild(explodeArray[i]);
                explodeArray[i].x= theNukes[i].x;
                explodeArray[i].y= theNukes[i].y;
            }//End of If Statement
        }//End of For Loop
    }//end of NukesExplode

}//end of class

}//end of package

Check if object moves in/out of browserscreen

In Actionscript3, when scrolling up and down on a page, how could I check, if an object becomes visible on the browserscreen and if an object moves out of it? Thanks a lot!

How to include Flash builder project as Library in android Studio?

I have been looking for a solution to this in stackover flow. How can i add a Flash builder project as a library in android studio? This is my situation.There are to projects dependent on each other.

  • Authentication module
  • Core app(this has been been migrated to flash builder)

How do i add the core app(which is in flash builder ) as a library to the authentication module?

Adobe Flash Builder Video Player not working

I am trying to get a video player to play in my application...this is my whole application:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ift.tt/rYUnH9" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       applicationComplete="init()"
                       showStatusBar="false"
                       creationComplete="myVid.play();">

    <s:VGroup>
        <s:VideoDisplay id="myVid" 
                        source="../assets/video.mp4"
                        height="250" 
                        width="250"
                        />
    </s:VGroup>

    <fx:Script> 
        <![CDATA[ 
        private function init():void  
        { 
        stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; 
        } 
        ]]> 
    </fx:Script> 
</s:WindowedApplication>

The video (video.mp4) is inside a folder I created called assets, how come this not appearing. I got this example from here:

http://ift.tt/1kVCyCP

Under "Using the Spark VideoDisplay control"

as3 move towards function jitters on Y axis

as the title suggests, I've written a move towards function that works perfectly fine, except that it jitters on the Y axis.

the problem happens when the function is operating on the Y axis and the difference between the starting value and the target value is less than that between the starting value and the value to return - meaning that the value has gone past its target. as this point, it's supposed to set the returning value to the target value, but for the most part it's not. except when it's operating on the x axis, in which case it works fine. it's really strange. anyway

here's the code I'm using for the function: public static function LookAt (thisX:Number, thisY:Number, targetX:Number, targetY:Number, speed:Number = 0, startRot:Number = 0):Number { // Get the distances between the two parsed points var xDif:Number = targetX - thisX; var yDif:Number = targetY - thisY;

        // Use a tangent formula to get the rotation to return in radians, then convert to degrees
        var rot:Number = Math.atan2(xDif, yDif) * 180/Math.PI * -1 - 180;

        // If a speed has been parsed
        if (speed != 0)
        {
            // Ensure the parsed starting rotation is between -180 and 180
            while (startRot > 180)
            {startRot -= 360;}
            while (startRot < -180)
            {startRot += 360;}

            // If the rotation previously calculated is less than the parsed starting rotation, 
            // return the starting rotation minus the speed. Otherwise, return the starting rotation
            // plus the speed
            return (rot > startRot) ? startRot + speed : startRot - speed;
        }
        else
        {
            return rot;
        }
    }

    public static function PointAround (axisPos:Number, angle:Number, speed:Number, axis:String = "x"):Number
    {
        // Convert the parsed angle into radians
        var fixedRot = angle * Math.PI / 180;

        // Return the parsed position plus speed multiplied by the sine of the angle in radians for the x axis,
        // or the cosine of the angle in radians for the y axis
        return (axis == "x") ? axisPos + speed * Math.sin(fixedRot) : axisPos + speed * Math.cos(fixedRot) * -1;
    }

    public static function PointTowards
    (thisX:Number, thisY:Number, targetX:Number, targetY:Number,
     speed:Number, axis:String = "x"):Number
    {
        // Use the LookAt function to calculate a rotation for later use in this function
        var workingAngle:Number = ExtraMath.LookAt (thisX, thisY, targetX, targetY);
        var toReturn;

        var thisVar:Number = (axis == "x") ? thisX : thisY;
        var targetVar:Number = (axis == "x") ? thisX : thisY;

        toReturn = ExtraMath.PointAround (thisVar, workingAngle, speed);
        // BUGGY LINE
        toReturn = (thisVar >= targetVar && toReturn <= targetVar
                    || thisVar <= targetVar && toReturn >= targetVar)
                    ? targetVar
                    : toReturn;

        return toReturn;
    }

and here's the code I'm using to test it:

public var c:Sprite;

public function TestZone() 
    {
        // constructor code
        stage.addEventListener(Event.ENTER_FRAME, Update);
    }

    private function Update (e:Event):void
    {
        c.x = ExtraMath.PointTowards(c.x, c.y, stage.mouseX, stage.mouseY, 5);
        c.y = ExtraMath.PointTowards(c.x, c.y, stage.mouseX, stage.mouseY, 5, "y");
    }

things I've tried already:

  • turning the line into regular a regular if statement with curly brackets and all, and tracing the variables thisY, targetY and toReturn after it has been operated on. the really annoying thing is that it turns out it sometimes actually returns the right number, but then proceeds to bug out again
  • Using an absolute value instead of stage.mouseY in testing. bug occurs as usual
  • Performing the function on the Y axis before the X axis. no difference
  • Changing the condition for setting the variables thisVar and targetVar to (axis != x) and switching the if/else values. do difference
  • probably more things I forgot about. I'm really stuck here. please help me

Flash CS6 Actionscript 3.0 Coloring Book

im trying to make a project, education coloring games for kids based android with flash, so i have trouble in my code im trying to listen tutorial from youtube and trying make it in my project in first frame its working but for next frame, have error i dont know why, im using same code and others name but still error can u help me for find where is my trouble

oh its link for download my project, http://ift.tt/1KHCWtk

so you can check my coding and others thanks, i hope someone help me if anyone can help and resolve coding in frame 2?

How to get byteStream from uploaded file using actionscript

My requirement is to get file stream details for uploaded file (.txt,.jpeg,*.doc etc). Currently I am using flash player 4 and flax specific version 9.0.124 that's why import flash.net.FileReferenceList and import flash.net.FileReference are available but import flash.net.FileStream is not available for me. I have searched on many sites but I didn't find any solution.So, If anybody have solution please reply its really urgent.

Flex4 PrintDataGrid variableRowHeight issue with custom itemRenderer

I am working with Flex 4.11 web application. I want to print the spark datagrid which has only one column with custom itemRenderer. You can see the following code :

<mx:PrintDataGrid id="taskDetailsDataGrid" width="100%" height="100%" headerHeight="0"
                      horizontalGridLines="false" styleName="printTaskDetails"
                      verticalGridLines="false" variableRowHeight="false" rowHeight="320">
        <mx:columns>
            <mx:DataGridColumn itemRenderer="itemRenderers.PrintTaskDetailsViewRenderer"/>
        </mx:columns>
    </mx:PrintDataGrid>

Problem is DataGrid, rowHeight can be different. Its depend on the data. If I set variableRowHeight="true" row height add some extra space. You can see the following image red rectangle:

enter image description here

If I set variableRowHeight="false" and provide rowHeight="320" then if data has more bigger size its overlap to next row. You can see the following image red rectangle:

enter image description here

How can I solve such problem.

Please reply me ASAP.

Thanks

Adobe AIR Application - full screen on inital run

I am very very new to Adobe Flash Builder with Flex and developing Adobe AIR Applications?

So far I have this:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ift.tt/rYUnH9" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       backgroundColor="0x000000"
                       >
</s:WindowedApplication>

How would I make this run full screen on intial run?

AS3: Can't move object I spawned, X and Y are "undefined properties"

I am using AS3 for the first time for a school assignment, and when I try to move an object I have spawned in the same frame, I get:

"1119: Access of possibly undefined property y through a reference with static type Class"

The error is referencing this line of code:

arrowUp.y += 2;

I get the same error if I try to move the object along the X-axis as well.

Full code of the function:

stage.addEventListener(Event.ENTER_FRAME, moveArrowUp);

function moveArrowUp(event:Event):void
{
    if(arrowUp_exists = true)
    {
    arrowUp.y += 2;
    }
}

If I use this same code to move an object that exists on the stage without being spawned with code, it works. If I put a trace within the if statement, it also works correctly.

"arrowUp_exists" is a boolean variable I created at the beginning of the frame so this code wouldn't run until arrowUp was spawned, which I am certain works because of the trace I tested.

All of the coding is being done on the timeline, due to that being how the teacher taught it and marks would be subtracted for not doing that (so I'm not using external classes for code, but I have exported all of my symbols to ActionScript).

Checkbox/RadioButton to select and deselect all checkboxes within a popup

I have a list of check boxes that I want to be able to select and deselect them all at once, how would |I do this using a check box?

The mxml of the check boxes I have are below:

<mx:VBox>
    <mx:CheckBox id="newCB" label="NEW" selected="true" change="onCheckboxChange(event)" />
    <mx:CheckBox id="tradeCB" label="TRADE" selected="true" change="onCheckboxChange(event)"/>
    <mx:CheckBox id="amendCB" label="AMEND" selected="true" change="onCheckboxChange(event)" />
    <mx:CheckBox id="cancelCB" label="CANCEL" selected="true" change="onCheckboxChange(event)" />
</mx:VBox>

mercredi 28 octobre 2015

as3 video buffer overflow(explosion)

ResolveVideoURL("rtmp://url");


function asyncErrorHandler(event:AsyncErrorEvent):void 
{ 
    trace(event.text); 
} 


function doPlay1() 
{
    //if( vns1 !=null )vns1.close(); vns1 = null ;

    vns1 = new NetStream(vnc1);
    vns1.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler); 


    mv1.attachNetStream(vns1);
    //mv1.smoothing = true;
    vns1.bufferTime = 1 ;
    vns1.play(CVL2);

}

function ResolveVideoURL( Url: String  )
{
    var tmpLOC : int = Url.lastIndexOf("/");

    CVL1 = Url.slice( 0 , tmpLOC ); 
    CVL2 = Url.slice( tmpLOC + 1 ); 

    vnc1.connect(CVL1);
}



has anybody ever get video return bufferLength overflow? like below image
it should be 1 , but get a large amount of it
it's encoding use vp6 , 800Kb(flow)
http://ift.tt/1PS9hWq

RegExp css url pattern group

I have the following css strings that I am trying to parse using a RegExp. I understand how to split on the comma. How do I work with the result to return an array or string?

I guess I'm missing the concept of capturing groups. These are css background properties.

this will split the commas /,\s*/ how would I then split the spaces to return a 2d array.

value = "0% 100%, 0% 0%, 100% 0%, 50% 50%";

This works great to get the first url. I would like to split on the comma /,\s*/ then split that result with /((?<=\")[^\"]*(?=\"))/

value = 'url("img/army_ant.png"),url("img/ants_menuNavButtton.png"),url("img/dirtbgtile.png")';

Thanks.

I am working in AS3 but JavaScript RegExp work just as well.

Thanks

1151: A conflict exists with definition, i dont understnad

I am having an error 1151 with AS3 it says 1151: A conflict exists with definition founditems in namespace internal. I don't understand what I have to change here it the script I am having the error with var founditems:Number = 0;

the full script is below THANKS :D

stop();

inventoryknife.alpha = 0;
inventoryaxe.alpha = 0;
inventoryesports.alpha = 0;


esports.addEventListener(MouseEvent.MOUSE_DOWN, objectFound);
axe.addEventListener(MouseEvent.MOUSE_DOWN, objectFound);
knife.addEventListener(MouseEvent.MOUSE_DOWN, objectFound);

var founditems:Number = 0;


can1.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
can1.addEventListener(MouseEvent.MOUSE_UP, dropObject);
can1.buttonMode = true;

can2.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
can2.addEventListener(MouseEvent.MOUSE_UP, dropObject);
can2.buttonMode = true;

can3.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
can3.addEventListener(MouseEvent.MOUSE_UP, dropObject);
can3.buttonMode = true;

can4.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
can4.addEventListener(MouseEvent.MOUSE_UP, dropObject);
can4.buttonMode = true;


brick1.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick1.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick1.buttonMode = true;

brick2.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick2.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick2.buttonMode = true;

brick3.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick3.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick3.buttonMode = true;

brick4.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick4.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick4.buttonMode = true;

brick5.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick5.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick5.buttonMode = true;

brick6.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick6.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick6.buttonMode = true;

brick7.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick7.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick7.buttonMode = true;

brick8.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick8.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick8.buttonMode = true;

brick9.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick9.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick9.buttonMode = true;

brick10.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
brick10.addEventListener(MouseEvent.MOUSE_UP, dropObject);
brick10.buttonMode = true;

crate1.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
crate1.addEventListener(MouseEvent.MOUSE_UP, dropObject);
crate1.buttonMode = true;

crate2.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
crate2.addEventListener(MouseEvent.MOUSE_UP, dropObject);
crate2.buttonMode = true;

crate3.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
crate3.addEventListener(MouseEvent.MOUSE_UP, dropObject);
crate3.buttonMode = true;


crate4.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
crate4.addEventListener(MouseEvent.MOUSE_UP, dropObject);
crate4.buttonMode = true;

tile1_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
tile1_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
tile1_mc.buttonMode = true;




{
var inventoryName:String = "inventory" + event.target.name;
var inventoryItem:DisplayObject = getChildByName(inventoryName);
event.target.alpha = inventoryItem.alpha = 100;
founditems ++;
event.target.alpha = 0;
if(founditems == 3)
{
door2_btn.addEventListener(MouseEvent.MOUSE_DOWN, escapeRoom);
}
}

Resolve errors with opensource project to publish .air package

I'm trying to edit the Lachhh giveaway tool on GitHub so I can make it an Extra Life Theme that I am trying to use for giveaways on Nov. 7th for my 24 hour charity stream. I can edit the individual flash animations like the menu with Flash CC but I can't compile all the components in FDT into the .air release. I'm also having a hard time finding where the music is, as I would like to replace it. I would love some help! I'm currently running into this issue.

I was able to get the project into eclipse (using FDT), but I couldn't resolve all the warnings and errors. I thought it might be able to do it all in Flash CC but it doesn't look like that's the case. Below are the six errors. I'm convinced that I'm importing or setting up the environment wrong as I'm you wouldn't publish a non-working project.

Errors Lists

The first one seems easy to fix, just generate a new certificate? When I saw that they were using the Apache Flex 4.9.1 FP11.1 en_US, which looks like Flash Player version 11.1 to me. And when I set it to use 4.9.1 with Flash 11.1, there is an extra error message

"Project Air SDK Version 3.1 does not match descriptor Air SDK Namespace 3.4"

Then there are 155 warnings mostly about "Could not resolve variable (maybe a dynamic member)" and "(maybe an XML element Name)" and "The import 'com.giveawaytool.effect.xxxxxx' is not used, found at line X column x"

It would be really awesome to get this working in time for my charity stream.

Passing variables to UnrealEngine from an .swf (and vice versa)

I'm working on a project along with 3D developers. I'm an Actionscript developer doing the front end (2D) controls for a 3D game.

  • The 3D game is on one screen and the 2D controls are on another
  • Both the 3D game and the 2D controls are running locally on the same machine
  • The 2D controls are in an Air application on a touch screen while the 3D game is in Unreal Engine on a bigger, non-touch screen

The 3D developers are working on the game itself in UE4's blueprint 'visual coding' thing.

How can I pass variables back and forth between the .swf and the Unreal game?

Thanks in advance.

Syntax error: expecting identifier before this. expecting colon before leftparen. expecting identifier before rightbrace

Scene 1, Layer 'script', Frame 1, Line 9    1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 9    1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 10   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 16   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 16   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 17   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 23   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 23   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 24   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 30   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 30   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 31   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 37   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 37   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 38   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 44   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 44   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 45   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 51   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 51   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 52   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 58   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 58   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 59   1084: Syntax error: expecting identifier before rightbrace.
Scene 1, Layer 'script', Frame 1, Line 65   1084: Syntax error: expecting identifier before this.
Scene 1, Layer 'script', Frame 1, Line 65   1084: Syntax error: expecting colon before leftparen.
Scene 1, Layer 'script', Frame 1, Line 66   1084: Syntax error: expecting identifier before rightbrace.

these errors (27 of them) show up and my stop command wont work, whats wrong with my code?? i'm new to flash action script, and i used a youtube tutorial to create the buttons (knapp) i refere to.

here's my code

stop();

//knappane til dei forskjellige planetane

//solen
solenKnappen.addEventListener(MouseEvent.CLICK, goToSolen);

function goToSolen(event: MouseEvent);void {
this.gotoAndStop("solen")
}

//merkur
merkurKnappen.addEventListener(MouseEvent.CLICK, goToMerkur);

function goToMerkur(event: MouseEvent);void {
this.gotoAndStop("merkur")
}

//venus
venusKnappen.addEventListener(MouseEvent.CLICK, goToVenus);

function goToVenus(event: MouseEvent);void {
this.gotoAndStop("venus")
}

//jorden
jordenKnappen.addEventListener(MouseEvent.CLICK, goToJorden);

function goToJorden(event: MouseEvent);void {
this.gotoAndStop("jorden")
}

//mars
marsKnappen.addEventListener(MouseEvent.CLICK, goToMars);

function goToMars(event: MouseEvent);void {
this.gotoAndStop("mars")
}

//jupiter
jupiterKnappen.addEventListener(MouseEvent.CLICK, goToJupiter);

function goToJupiter(event: MouseEvent);void {
this.gotoAndStop("jupiter")
}

//saturn
saturnKnappen.addEventListener(MouseEvent.CLICK, goToSaturn);

function goToSaturn(event: MouseEvent);void {
this.gotoAndStop("saturn")
}

//uranus
uranusKnappen.addEventListener(MouseEvent.CLICK, goToUranus);

function goToUranus(event: MouseEvent);void {
this.gotoAndStop("uranus")
}

//neptun
neptunKnappen.addEventListener(MouseEvent.CLICK, goToNeptun);

function goToNeptun(event: MouseEvent);void {
this.gotoAndStop("neptun")

Action Script 3 error 1023: Implication Override & error 1021: Duplication function Definition. Look here and cant find the answer

Help

I'm a university student currently studying action script 3 flash game coding and I've come across the two coding problems that are within the title. 1023 and 1021.

I've looked at multiple forums and posts (even on here) to find a solution but everything I try just doesn't seem to work at all. I'm tearing my hair out over this I just want it to work. If anyone can help me out by point out what the heck is wrong I'd greatly appreciated it!

var loader:URLLoader;
var allWords:Array;
var thisWord:String;
var textContainer:MovieClip
var textFields:Array;
var textStyle:TextFormat;
var underline:MovieClip;
var numCorrect:uint;
var totalLetters:uint;
var misses:uint;
var missiesToLose:uint;


function initializeGame():void
{
loader = new URLLoader();
allWords = new Array();

textContainer = new MovieClip();
textFields = new Array()

textStyle = new TextFormat();

textStyle.font = "Courier New";
textStyle.size = 48;
textStyle.bold = true;

guesses_txt.text = "";

numCorrect = 0;

textContainer.y = 320.30;
addChild(textContainer);

loader.load(new URLRequest("words.txt"));
loader.addEventListener(Event.COMPLETE, textLoaded);
guess_btn.addEventListener(MouseEvent.CLICK, guess);
 }    

  function textLoaded(event:Event):void
{
var tempText:TextField;
var stringOfWords:String = event.target.data;
allWords = stringOfWords.split(",");
thisWord = allWords[7]; 
totalLetters = thisWord.length;

//characters loop
for(var i:uint = 0; i < thisWord.length; i++)
{
    tempText = new TextField();
    tempText.defaultTextFormat = textStyle; //font type
    tempText.name = "textField" + i; 


    tempText.width = 48;
    tempText.x = i * tempText.width;
    tempText.selectable = false;
    textContainer.addChild(tempText);
    textFields.push(tempText);

    if(thisWord.charAt(i) != " ")
    {
        underline = new Underline();
        underline.x = tempText.x + tempText.width /3;
        underline.y = tempText.y + tempText.height/2 + 5;
        textContainer.addChild(underline);
    }
  }
  textContainer.x = stage.stageWidth /2 - textContainer.width/2;
   }

   function guess(Event:MouseEvent):void
   {
var wordLC:String = thisWord.toLowerCase();

if(guess_txt.text != "") 
{
    if(wordLC.indexOf(guess_txt.text) != -1)
    {
        for(var i:uint = 0; i < textFields.length; i++)
        {
            if(wordLC.charAt(i) == guess_txt.text)
            {
                textFields[i].text = thisWord.charAt(i);
                numCorrect ++;
                if(numCorrect >= totalLetters)
                {
                    gotoAndPlay(2);
                }
            }
        }
    }
    else if(guesses_txt.text == "") 
    {
        guesses_txt.appendText(guess_txt.text);
    }
    else
    {
        guesses_txt.appendText("," + guess_txt.text)
    }
}
guess_txt.text = "";
}

initializeGame();

Flex 4

I try to display a text with a Label component. In some case text is longer than label weight. So I hope to use something like word-wrap option to display text on 2 lines.

 <s:BorderContainer height="26" width="100%" borderStyle="inset" 
                                   id="bcDos"
                                   >

                    <s:Label text="{phpImportant}" textAlign="center"
                             fontWeight="bold" color="#FF0730" fontSize="12"
                             paddingBottom="1" paddingTop="1"
                             width="100%" height="100%" maxDisplayedLines="2"

                             />
                </s:BorderContainer>

With this code, only 1 line is displaying. Indeee

With this code,if there is more text than the label can display, Label truncate the text for me with a truncation indicator such as "...". In my dream I'd like to have automatic word-wrap on 2 lines.

Thanks for helping.

Button to check if the movieclip's COLORS match [AS3]

I'm doing a project which for now it's about coloring shapes, the user will have to pick the color and click on the shapes to apply the color and they may click a button to check if it's correct. I manage to do all these but not the button. How do i write the IF/Else or Switch/Case statement for the "check1_btn" button which im going to click to check if the movieclip's colors match the color i pick and if it is matched, it will trace "good" else it will just trace "oops!"

This is the codes for selecting and dropping the colors :

import flash.events.MouseEvent;
import flash.geom.ColorTransform;

var SelColor:Number = 0xEFEFEF;

// Select Color

redpick_mc.addEventListener(MouseEvent.CLICK,RedS);
function RedS (event:MouseEvent):void
{
    SelColor = 0xE14938;
}

orangepick_mc.addEventListener(MouseEvent.CLICK,OrangeS);
function OrangeS (event:MouseEvent):void
{
    SelColor = 0xFBA026;
}

purplepick_mc.addEventListener(MouseEvent.CLICK,PurpleS);
function PurpleS (event:MouseEvent):void
{
    SelColor = 0x553982;
}

greenpick_mc.addEventListener(MouseEvent.CLICK,GreenS);
function GreenS (event:MouseEvent):void
{
    SelColor = 0x61BD6D;
}

bluepick_mc.addEventListener(MouseEvent.CLICK,BlueS);
function BlueS (event:MouseEvent):void
{
    SelColor = 0x2C82C9;
}

yellowpick_mc.addEventListener(MouseEvent.CLICK,YellowS);
function YellowS (event:MouseEvent):void
{
    SelColor = 0xFAC51C;
}

// Fill Color

bigdrop_mc.addEventListener(MouseEvent.CLICK, bdrop);
meddrop_mc.addEventListener(MouseEvent.CLICK, mdrop);
smalldrop_mc.addEventListener(MouseEvent.CLICK, sdrop);

function bdrop(event:MouseEvent):void
{
    var DrawCol = new ColorTransform ();
    DrawCol.color = SelColor;
    bigdrop_mc.transform.colorTransform = DrawCol;
}

function mdrop(event:MouseEvent):void
{
    var DrawCol = new ColorTransform ();
    DrawCol.color = SelColor;
    meddrop_mc.transform.colorTransform = DrawCol;
}

function sdrop(event:MouseEvent):void
{
    var DrawCol = new ColorTransform ();
    DrawCol.color = SelColor;
    smalldrop_mc.transform.colorTransform = DrawCol;
}

This is what i'm trying to do, but failed lol :

check1_btn.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);

function fl_MouseClickHandler(event:MouseEvent):void
{
    if  (
        bigdrop_mc.transform.colorTransform.color = 0x61BD6D;

        meddrop_mc.transform.colorTransform.color = 0xFAC51C;

        smalldrop_mc.transform.colorTransform.color = 0xE14938;)
    {

        trace("Good");

    }   
    else 
    {
        trace("Oops..");
    }
}

which way is good to check the string variable holding boolean value in as3?

        var myString:String = "true";
        if (myString.toLowerCase() == "true")

or

        if (myString is Boolean)

or

        if (myString == Boolean)

Which one is good to check the string variable is holding boolean values (true or false). Or which one is right?

Thanks...

"Call to a possibly undefined method" - big project

im working on a side scrolling game project but ive been struggling with AS files. 1st of all i did not code on the main time line frame one, i use external as files for the entire project.

So far i have 2 separate as files, main one named Tuan.as and the other one Enemy.as

i have no problem running with Tuan.as file alone however when i decided to add more features to the game like adding enemy by using another as file called Enemy.as and i couldnt import them properly. i got the error "Call to a possibly undefined method addEnemytoLevel1"

Here is the code of my entire game, the first file Tuan.as:

package  {

import flash.display.MovieClip;
import flash.media.SoundChannel;
import flash.media.Sound;
import flash.events.*;
import flash.geom.*;
import flash.ui.*;
import flash.events.*;

public class Tuan extends MovieClip {


    public var myChannel:SoundChannel = new SoundChannel();
    public var mySound:Sound = new general();



    public var leftPressed:Boolean = false;
    public var rightPressed:Boolean = false;
    public var upPressed:Boolean = false;
    public var downPressed:Boolean = false;

    public var leftBumping:Boolean = false;
    public var rightBumping:Boolean = false;
    public var upBumping:Boolean = false;
    public var downBumping:Boolean = false;

    public var leftBumpPoint:Point = new Point(-30, -55);
    public var rightBumpPoint:Point = new Point(30, -55);
    public var upBumpPoint:Point = new Point(0, -120);
    public var downBumpPoint:Point = new Point(0, 0);

    public var scrollX:Number = 0;
    public var scrollY:Number = 500;

    public var xSpeed:Number = 0;
    public var ySpeed:Number = 0;

    public var speedConstant:Number = 4;
    public var frictionConstant:Number = 0.9;
    public var gravityConstant:Number = 1.8;
    public var jumpConstant:Number = -35;
    public var maxSpeedConstant:Number = 18;

    public var doubleJumpReady:Boolean = false;
    public var upReleasedInAir:Boolean = false;

    private var keyCollected:Boolean = false;
    private var keyCollected2:Boolean = false;
    private var keyCollected3:Boolean = false;
    private var keyCollected4:Boolean = false;
    private var keyCollected5:Boolean = false;
    private var keyCollected6:Boolean = false;
    private var keyCollected7:Boolean = false;
    private var keyCollected8:Boolean = false;

    var enemyList:Array = new Array();      
    public var doorOpen:Boolean = false;

     public var nakedboard:Boolean = false;
     public var currentLevel:int = 1;

    addEnemiesToLevel1();

    public function addEnemiesToLevel1():void{
    addEnemy(620, -115);
    addEnemy(900, -490);
    addEnemy(2005, -115);
    addEnemy(1225, -875);
    }

    public function Tuan() {


        myChannel = mySound.play(0, 9999);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
        stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);

        stage.addEventListener(Event.ENTER_FRAME, loop);

    }


    public function loop(e:Event):void{
        if(back.collisions.hitTestPoint(player.x + leftBumpPoint.x, player.y + leftBumpPoint.y, true)){
            //trace("leftBumping");
            leftBumping = true;
        } else {
            leftBumping = false;
        }

        if(back.collisions.hitTestPoint(player.x + rightBumpPoint.x, player.y + rightBumpPoint.y, true)){
            //trace("rightBumping");
            rightBumping = true;
        } else {
            rightBumping = false;
        }

        if(back.collisions.hitTestPoint(player.x + upBumpPoint.x, player.y + upBumpPoint.y, true)){
            //trace("upBumping");
            upBumping = true;
        } else {
            upBumping = false;
        }

        if(back.collisions.hitTestPoint(player.x + downBumpPoint.x, player.y + downBumpPoint.y, true)){
            //trace("downBumping");
            downBumping = true;
        } else {
            downBumping = false;
        }   


        if(leftPressed){
            xSpeed -= speedConstant;
            player.scaleX = -1;

        } else if(rightPressed){
            xSpeed += speedConstant;
            player.scaleX = 1;
        }


        if(leftBumping){
            if(xSpeed < 0){
                xSpeed *= -0.5;
            }
        }

        if(rightBumping){
            if(xSpeed > 0){
                xSpeed *= -0.5;
            }
        }

        if(upBumping){
            if(ySpeed < 0){
                ySpeed *= -0.5;
            }
        }

        if(downBumping){ //if the character touches the floor
            if(ySpeed > 0){ 
                ySpeed = 0; //set the y speed to zero
            }
            if(upPressed){ //and if the up arrow is pressed
                ySpeed = jumpConstant; //set the y speed to the jump constant
            }

            //DOUBLE JUMP
            if(upReleasedInAir == true){
                upReleasedInAir = false;
            }
            if(doubleJumpReady == false){
                doubleJumpReady = true;
            }
        } else { //if we are not touching the floor

            ySpeed += gravityConstant; //accelerate downwards

            if(upPressed == false && upReleasedInAir == false){
                upReleasedInAir = true;
                //trace("upReleasedInAir");
            }
            if(doubleJumpReady && upReleasedInAir){
                if(upPressed){ //and if the up arrow is pressed
                    //trace("doubleJump!");
                    doubleJumpReady = false;
                    ySpeed = jumpConstant; //set the y speed to the jump constant
                }
            }

        }

        if(xSpeed > maxSpeedConstant){ //moving right
            xSpeed = maxSpeedConstant;
        } else if(xSpeed < (maxSpeedConstant * -1)){ //moving left
            xSpeed = (maxSpeedConstant * -1);
        }

        xSpeed *= frictionConstant;
        ySpeed *= frictionConstant;

        if(Math.abs(xSpeed) < 0.5){
            xSpeed = 0;
        }

        scrollX -= xSpeed;
        scrollY -= ySpeed;

        back.x = scrollX;
        back.y = scrollY;

        cave.x = scrollX * 0.2;
        cave.y = scrollY * 0.2;


if (nakedboard == false){
            if(player.hitTestObject(back.nakedboard)){
                back.nakedboard.gotoAndPlay(2);

            }
        }
        if(keyCollected == false ){
            if(player.hitTestObject(back.puzzle.redKey)){
                back.puzzle.redKey.visible = false;
                keyCollected2 = true;

                trace("need next key")

                }
            }
        if (keyCollected2 == true ){
            if(player.hitTestObject(back.puzzle.orangeKey)){
                back.puzzle.orangeKey.visible = false;
                keyCollected3 = true;

            } 
        }

        if(doorOpen == false){
            if(keyCollected3 == true){
                if(player.hitTestObject(back.puzzle.lockedDoor)){
                    back.puzzle.lockedDoor.gotoAndStop(2);
                    doorOpen = true;

                    trace("door open");
                }
            }
        }       


    }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    public function gotoLevel2():void{
        back.nakedboard.gotoAndStop(1);
        back.puzzle.gotoAndStop(2);
        back.visuals.gotoAndStop(2);
        back.collisions.gotoAndStop(2);
        scrollX = 0;
        scrollY = 500;
        back.puzzle.lockedDoor.gotoAndStop(1);
        /*back.other.doorKey1.visible = true;*/


    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function gotoLevel3():void{

        back.puzzle.gotoAndStop(3);
        back.visuals.gotoAndStop(3);
        back.collisions.gotoAndStop(3);
        scrollX = 0;
        scrollY = 500;

    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public function nextLevel():void{
        currentLevel++;
        trace("Next Level: " + currentLevel);
        if(currentLevel == 2){
           gotoLevel2();
        }
        // can be extended...
         else if(currentLevel == 3) { 
             gotoLevel3(); 
             }  
    }

    public function addEnemy(xLocation:int, yLocation:int):void
{
    var enemy:Enemy = new Enemy(xLocation, yLocation);
    back.addChild(enemy);

    enemy.addEventListener(Event.REMOVED, enemyRemoved);
    enemyList.push(enemy);
}
    public function enemyRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED, enemyRemoved);
enemyList.splice(enemyList.indexOf(e.currentTarget), 1);
}

    public function keyDownHandler(e:KeyboardEvent):void{
        if(e.keyCode == Keyboard.LEFT){
            leftPressed = true;

        } else if(e.keyCode == Keyboard.RIGHT){
            rightPressed = true;

        } else if(e.keyCode == Keyboard.UP){
            upPressed = true;

        } else if(e.keyCode == Keyboard.DOWN){
            downPressed = true;
            if(doorOpen && player.hitTestObject(back.puzzle.lockedDoor)){
                nextLevel();
                myChannel.stop();

            }
        }   
    }

    public function keyUpHandler(e:KeyboardEvent):void{
        if(e.keyCode == Keyboard.LEFT){
            leftPressed = false;

        } else if(e.keyCode == Keyboard.RIGHT){
            rightPressed = false;

        } else if(e.keyCode == Keyboard.UP){
            upPressed = false;

        } else if(e.keyCode == Keyboard.DOWN){
            downPressed = false;
        }   
    }
}

}

and this is the Enemy.as file:

package{
import flash.display.MovieClip;
import flash.events.Event;

public class Enemy extends MovieClip{

    public function Enemy(xLocation:int, yLocation:int)
    {
        // constructor code
        x = xLocation;
        y = yLocation;

        addEventListener(Event.ENTER_FRAME, loop);
    }

    public function loop(e:Event):void
    {
        //the looping code goes here
    }

    public function removeSelf():void
    {
        trace("remove self");
        removeEventListener(Event.ENTER_FRAME, loop); //stop the loop
        this.parent.removeChild(this); //tell this object's "parent object" to remove this object
    }
}

}

im not really good at AS if dont wanna say very bad, i cant figure out how to get it work, so much appreciate for help.

mardi 27 octobre 2015

Is there an API to get a more precise time for profiling?

In the Flash API there is the getTimer() method that returns the time in milliseconds since the SWF started. I was writing PHP recently and there is a much more precise method called, microtime() that gets the microsecond time. Does Flash have anything more precise than getTimer();

animated snow from AS3 to JS

I have a project that I rebuilt in flash using the canvas option. Everything is working out great! I just have on issue, the project in flash has a function that I used to create some dynamic snow. I ported this function over to JS, and while it works, it cause the animation to be very choppy on mobile devices. Anyone have any suggestions as to what I might try to improve the performance? Maybe this is just the complete wrong way of doing something like this.

Here is converted JS code.

function snowing(){
var scale = Math.random()*.6; 
var _sf = new lib.snowflake();
_sf.x=Math.random()*1024; _sf.scaleX=scale;
_sf.scaleY=scale;
var speed = Math.random()*10;
var RA = new Array(-1,1); 
var lf = RA[Math.round(Math.random())]; 
my_stage.addChild(_sf); 
setInterval(function(){snowfall()}, 33);

function snowfall() { _sf.y+=speed; 
_sf.rotation+=Math.random()*10; _sf.x+=(Math.random()*2)*lf; }
}

    //make it snow
setInterval(function(){snowing()}, 33);

I found this but it seems to snow over the entire page, not just the canvas tag. http://ift.tt/1MrmWTG

How do detect when someone makes a call from an Android device in an AIR application?

I want to be able to read the contact number of the person to whom the call was made and read when the call ends. I have been googling but couldn't really find anything. How can I achieve this? any help is greatly appreciated.

Actionscript mcrypt_decrypt

I'm working through a decryption function and have hit a wall. I'm not very experienced with Actionscript but when I run this function it goes on an infinite loop.

private function mcrypt_decrypt(param1:Array, param2:Number,param3:Number): Array {
 var _loc4_:* = -9.57401312E8;
 while(_loc4_)
 {
    var param3:Number = param3 - ((param2 << 4 ^ param2 >>> 5) + param2 ^ _loc4_ + param1[_loc4_ >>> 11 & 3]);
    _loc4_ = _loc4_ - -1640531527;
    var param2:Number = param2 - ((param3 << 4 ^ param3 >>> 5) + param3 ^ _loc4_ + param1[_loc4_ & 3]);
 }
 return [param2,param3];
}

From testing I see that loc4 starts as -9.57401312E8 and then as iteration continues -1640531527 is removed each time, but in what case would this satisfy the while condition? Any ideas?

Get downloads & file browsing requests from HTMLFrame

I am able to load and display files using the HTMLLoader class. http://ift.tt/1NxNP5y

Problem is, when a user navigates to a download link or an upload button, nothing happens. I heard somewhere that any downloads get sent over to the user's main document folder. Anyway to intercept this and get some details? Someone in my browsing history suggested to somehow get it using the Socket class to fetch it's data and control where it would go using the File class. I couldn't make out the demonstration.

Bonus question...what properties do I have to set to make Google understand that this browser is not a bot? I get this in plain text when trying to navgiate to http://www.google.com . It's other services work completely fine though.

Google Sorry...

We're sorry...

... but your computer or network may be sending automated queries. To protect our users, we can't process your request right now.

asSQL API - 1046: Type was not found or was not a compile-time constant: [mx.rpc]::IResponder

I'm trying to use an external swc that someone made off the net. It's a mysql driver for actionscript 3. http://ift.tt/1RbCr04

Problem is, even after linking the swc in Adobe Flash CC under Actionscript 3 > Properties > Library path, I get an error saying it can't find [mx.rpc]::IResponder.

Does anyone have any experience with this lib or know what could be the problem? Is this due to me not using adobe flex? I found Missing [mx.rpc]::IResponder but that's saying I need a library from Adobe Flash Builder 4. Kind of rusty on compiler errors. [And the internet at my place has been limited as far as downstream goes, so it's about a 3 hour download to get it.]

Random text generation to stage?

I have created a simple game with a player and obstacles moving across the screen. However, I would like to add some random letters to the stage which appear and can be collected by the player. The letters should be part of an array and will eventually complete the full word at the bottom of the screen (like hangman). Can anyone give advice on how I could achieve this? I don't know where to start.

FlexPrintJob multi page print issue in flex

I am working in Flex 4.11 web application. I am using Spark DataGroup component to display list based data. Here I am using itemrenderer to display data. When I am trying to print this Datagroup it is being print into more than one page.

So the problem is How can I identify which will be the next page at the time of printing. I have seen an example of PrintDataGrid but it is has the nextPage(), validNextPage() functions. But for my point of view how can I identify it.I want to show page number in bottom for every page.

lundi 26 octobre 2015

How to check if two objects are same color in a hit test in AS3

My program is a simple game where colored rectangles fall down the screen. Your player changes color depending on what button you click on, the aim is to make your player the same color as the falling object. How do i do a hit test object and check if the two colors are the same.

Here is my code:

import flash.geom.ColorTransform;
import flash.events.TimerEvent;

var rectangle:Shape = new Shape;
var RecTimer:Timer = new Timer(5);
var RecSTimer:Timer = new Timer(800);
var collision:Timer = new Timer(10,1000);
collision.start()
RecTimer.addEventListener(TimerEvent.TIMER, onTimer);
RecTimer.start();
RecSTimer.addEventListener(TimerEvent.TIMER, onSpawnTimer);
RecSTimer.start();
collision.addEventListener(TimerEvent.TIMER, fcollision)


function fcollision(e:TimerEvent):void {
    for each(var rectangle:Shape in rectangles)
    {
        if (mcPLayer.hitTestObject(rectangle)) {

       }
        }
    }

var rectangles:Array = []; // a list of all the rectangles we've made so far
 function spawnRectangle():void {
    var rectangle:Shape = new Shape();
    rectangle.graphics.beginFill(randomColor()); // choosing the colour for the fill, here it is red
    rectangle.graphics.drawRect(0, 10, 480, 45.49); // (x spacing, y spacing, width, height)
    rectangle.graphics.endFill();
    addChild(rectangle); // adds the rectangle to the stage
    rectangles.push(rectangle); // adds the rectangle to our list of rectangles




}
var colors:Array = [0xFF0000, 0x00FF00, 0x0000FF];

function randomColor():uint
{
    return colors[int(Math.random()*colors.length)];
}
function moveAllRectangles():void {
    for each (var rectangle:* in rectangles) {
            rectangle.y +=2;
        if (rectangle.y == 550){
            removeChild(rectangle)
        }

                    }

    }

function onTimer(e:TimerEvent):void {
        moveAllRectangles();

}
function onSpawnTimer(e:TimerEvent):void {
    spawnRectangle();
}
btnRed.addEventListener(MouseEvent.CLICK, fred);
btnGreen.addEventListener(MouseEvent.CLICK, fgreen);
btnBlue.addEventListener(MouseEvent.CLICK, fblue);

function fred (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0xFF0000;
mcPLayer.transform.colorTransform = myColorTransform;
}

function fgreen (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x00FF00;
mcPLayer.transform.colorTransform = myColorTransform;
}
function fblue (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x0066CC;
mcPLayer.transform.colorTransform = myColorTransform;
}

function delayedFunctionCall(delay:int, func:Function) {
    var timer:Timer = new Timer(delay, 1);
    timer.addEventListener(TimerEvent.TIMER, func);
    timer.start();
}

RegExp to find first letter of words before @

I'm trying to capitalize the first letter of names in an email address. For example, john.doe@example.com would become John.Doe@example.com. I have some regex that will find the first letter of all the words, but it includes the results after the @.

/(\b[a-z])/g

Is there a way to get just the results before the @? I'm doing this in ActionScript but it's pretty standard.

If I have to, I can just use split('@') to break the email address up into an array of 2 elements, perform the change on the first element, then put them back together into a single string again. I'd rather just use regex to simplify it if I can.

AS3 - Keyboard Event Not working for certain Keys

So this is weird, I'm using the exact same Key class that Kongregate.com gives you when you do their "Shootorials." It works nicely for arrow keys, but not so much when you try to use WASD controls. I couldn't get it to recognize the keyCode, so I started typing trace(); statements in the keyPressed event handler.

It turns out that my arrow keys, and some of my other keys like 'D', and 'G' will trigger the event. However other keys don't work. 'A', 'S'.

Why is my class working for some keys and not other keys?

Source Code

package {

import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;

public class Key {

    private static var initialized:Boolean = false;
    private static var keysDown:Object = new Object();  // stores key codes of all keys pressed

    public static function initialize(stage:Stage) {
        if (!initialized) {
            // assign listeners for key presses and deactivation of the player
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
            stage.addEventListener(Event.DEACTIVATE, clearKeys);
            // mark initialization as true so redundant
            // calls do not reassign the event handlers
            initialized = true;
            trace("Initialized [Keys]");
        }
    }


    public static function isDown(keyCode:uint):Boolean 
    {
        return Boolean(keyCode in keysDown);
    }


    private static function keyPressed(event:KeyboardEvent):void {
        trace("Keyboard Event Trigger");
        keysDown[event.keyCode] = true;
    }


    private static function keyReleased(event:KeyboardEvent):void {
        if (event.keyCode in keysDown) {
            delete keysDown[event.keyCode];
        }
    }


    private static function clearKeys(event:Event):void {
        // clear all keys in keysDown since the player cannot detect keys being pressed or released when not focused
        keysDown = new Object();
    }
}

}

Access to undefined property itemRenderer (Keyboard Event)

I am trying to get the following code to run when I hit enter on a row within a data grid, it works when I click on the row (ListEvent) but how would I enable this to work when the enter key is hit (KeyboardEvent). I have the enter key working although it throws this error every time

 var item:Object = evt.itemRenderer.data;
    openWorkflowItem(item.date.date, item.workFlowID);
    $multiEdit = false;

    if (target === currentWorkflowItems)
    {
        $histFilter['sym'] = item.sym;
        histSym.text = item.sym;
        applyHistFilters();
    }

AS3 Checking an Array to see if a value exists

Ive googled this quite extensively and have had no success with this problem. I have an array:

public var myMap: Array = [ //Set tile locations
                                                [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                                                [1, 0, 0, 0, 13, 2, 9, 10, 6, 1],
                                                [1, 0, 0, 0, 0, 0, 2, 2, 2, 1],
                                                [1, 0, 2, 4, 2, 0, 3, 0, 7, 1],
                                                [1, 3, 2, 2, 0, 3, 2, 0, 0, 1],
                                                [1, 0, 3, 5, 13, 0, 8, 2, 0, 1],
                                                [1, 11, 2, 3, 2, 0, 2, 12, 0, 1],
                                                [1, 0, 2, 2, 2, 3, 2, 0, 2, 1],
                                                [1, 3, 0, 3, 0, 11, 2, 0, 10, 1],
                                                [1, 2, 2, 0, 2, 0, 2, 2, 2, 1],
                                                [1, 3, 2, 0, 3, 0, 0, 2, 10, 1],
                                                [1, 12, 0, 0, 13, 2, 3, 0, 0, 1],
                                                [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
                                        ];

And I want to check if a value exists and if it does not exist, i want to do something.

What I have is this function that I tried based on previous questions:

public function levelTwo() {
  if(myMap.indexOf(10)==-1) {
    trace('win')
  }
}
;
I can't seem to get it working though. It is tracing 'win' as soon as i run the game.

Any help would be appreciated.

Global variable set in Loader Complete event gives null outside in AS3

Hi I am trying to access a public class level variable after it is set from the Loader COMPLETE event. But getting null outside. You can see the code below.

I am calling the following code on Loader Complete

request = new URLRequest((this._cueCard.folderDirectory + String(this.extensionsURL_array[_index])));
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function (_arg1:Event){
    var _local2:Object = loader.content;
    _local2.addEventListener("CLOSE", closeFromExtensions);
    extensions_array[_extensionName] = _local2;
    extensionsBar.loadExtension(extensions_array[_extensionName]);
    this.extensionContent = extensions_array[_extensionName];
    trace("in extension manager 2: " + this.extensionContent);
});
loader.load(request);

where this.extensionContent is a public class level variable of ExtensionManager class. It prints the following value in the trace statement.

in extension manager 2: [object Share]

I am accessing the public property from some other class in the following code

private function updateShareExtensionUrl(){

    var currentExtension:String = this.extensionsManager.currentExtensionName;
    if(currentExtension != null && currentExtension.toLowerCase() == "share"){
        var shareExtension:IMyInterface =  this.extensionsManager.extensionContent as IMyInterface;
        if (shareExtension != null) {
            trace("video player sending update to share extension");
            shareExtension.scissorsClicked(true);
        }
        else{
            trace("getting null with this.extensionsManager.extensionContent");
        }
    }
    else{
        trace("share is not opened");
    }
}

I call the above function many times after the Complete event is completed. But always get the value of the extensionContent as null in the above function and always print the following value of the trace statement.

getting null with this.extensionsManager.extensionContent

When I set the same value in some other function of the ExtensionManager class, I get the object as not null in the updateShareExtensionUrl function.

Not sure, what I am missing. Could you please help?

Netstream Get Audio Only

Netstream As sound only?

I'm trying to put the sound coming from a netstream into a Sound variable so I can visualize it like in this tutorial. Adobe ActionScript 3.0 * Accessing raw sound data

Problem is, search results only find how to attach a video to a video object, and not a sound object.

private function handleAccept(e:MouseEvent):void 
    {
    myNS.attachAudio(Microphone.getEnhancedMicrophone(0));
    myNS.publish("audio");

    var s:Sound = new Sound(theirNS.play("audio"));//??
    s.play(); 

    //Custom tranformation ahead..
    }

dimanche 25 octobre 2015

Comparing Strings in As3

I'm currently coding a game for an assignment and I need help comparing Strings. The question in the game asks the users to type out a specific sequence on their keyboard. I have provided a sequence "SWAGAFFAD" and I want my code to compare a the values that people might enter. If they get the sequence correct I want them to be able to proceed to the next question and if they don't type in the exact sequence they just get an error message come up. Just not sure how to code this. Can someone help me out? Assuming I'd need an IF ELSE statement?? Thanks in advance!!!

How to create hit box for rectangle that has been drawn within code in AS3

So I have a program that spawns in rectangles with a random color and then proceeds to fall down the screen. I also have a player that changes color depending on what button you click. The problem is getting the HitTestObject to work on an object that is drawn from code. Here is the code:

  import flash.geom.ColorTransform;
import flash.events.TimerEvent;

var rectangle:Shape = new Shape;
var RecTimer:Timer = new Timer(5);
var RecSTimer:Timer = new Timer(800);
var collision:Timer = new Timer(10,1000);
collision.start()
RecTimer.addEventListener(TimerEvent.TIMER, onTimer);
RecTimer.start();
RecSTimer.addEventListener(TimerEvent.TIMER, onSpawnTimer);
RecSTimer.start();
collision.addEventListener(TimerEvent.TIMER, fcollision)


function fcollision(e:TimerEvent):void {
    if (mcPLayer.hitTestObject (rectangle)) {
        trace("hit")
    }
}


var rectangles:Array = []; // a list of all the rectangles we've made so far
 function spawnRectangle():void {
    var rectangle:Shape = new Shape();
    rectangle.graphics.beginFill(randomColor()); // choosing the colour for the fill, here it is red
    rectangle.graphics.drawRect(0, 10, 480, 45.49); // (x spacing, y spacing, width, height)
    rectangle.graphics.endFill();
    addChild(rectangle); // adds the rectangle to the stage
    rectangles.push(rectangle); // adds the rectangle to our list of rectangles
     var rect:Rectangle = rectangle.getBounds(rectangle);


}
var colors:Array = [0xFF0000, 0x00FF00, 0x0000FF];

function randomColor():uint
{
    return colors[int(Math.random()*colors.length)];
}
function moveAllRectangles():void {
    for each (var rectangle:* in rectangles) {
            rectangle.y +=2;
        if (rectangle.y == 550){
            removeChild(rectangle)
        }

                    }

    }

function onTimer(e:TimerEvent):void {
        moveAllRectangles();

}
function onSpawnTimer(e:TimerEvent):void {
    spawnRectangle();
}
btnRed.addEventListener(MouseEvent.CLICK, fred);
btnGreen.addEventListener(MouseEvent.CLICK, fgreen);
btnBlue.addEventListener(MouseEvent.CLICK, fblue);

function fred (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0xFF0000;
mcPLayer.transform.colorTransform = myColorTransform;
}

function fgreen (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x00FF00;
mcPLayer.transform.colorTransform = myColorTransform;
}
function fblue (e:MouseEvent):void{
 var myColorTransform = new ColorTransform();
myColorTransform.color = 0x0066CC;
mcPLayer.transform.colorTransform = myColorTransform;
}

function delayedFunctionCall(delay:int, func:Function) {
    var timer:Timer = new Timer(delay, 1);
    timer.addEventListener(TimerEvent.TIMER, func);
    timer.start();
}

Actionscript 3 Using Regular Expressions to replace words in string

I'm working on a project that involves creating an Adobe Flash application that changes the tense of the text in an input text box. The original example text is: "The city of Atlantis is lost. The werewolves were to blame. I am saddened and so were my friends. The residents and Atlantis are unhappy too. It is such a waste."

I've figured out how to make it past tense and mostly present tense. But I can't seem to figure out how to change the part "I was" from past tense back to present tense (I am). Please help.

    original_btn.addEventListener(MouseEvent.CLICK, ConvertOriginal);
    past_btn.addEventListener(MouseEvent.CLICK, ConvertPast);
    present_btn.addEventListener(MouseEvent.CLICK, ConvertPresent);

    function ConvertOriginal(e:MouseEvent):void {
        body_txt.text = "The city of Atlantis is lost. The werewolves were to blame. I am saddened and so were my friends. The residents and Atlantis are unhappy too. It is such a waste."; 
}
    function ConvertPast(e:MouseEvent):void {
        var myPattern1:RegExp = /\s(is|am)\s/g;  
        var str:String = body_txt.text;
        body_txt.text = body_txt.text.replace(myPattern1, " was ");
        var myPattern2:RegExp = /\sare\s/g;  
        body_txt.text = body_txt.text.replace(myPattern2, " were "); 
}
    function ConvertPresent(e:MouseEvent):void {
        var myPattern1:RegExp = /\swas\s/g;  
        var str:String = body_txt.text;
        body_txt.text = body_txt.text.replace(myPattern1, " is ");
        var myPattern2:RegExp = /was/g;
        body_txt.text = body_txt.text.replace(myPattern2, " I am ");
        var myPattern3:RegExp = /\swere\s/g;  
        body_txt.text = body_txt.text.replace(myPattern3, " are ");
}

Masked layer in flash refuses to change colour: Actionscript 3

So this particular issue is now driving my up the wall.

I have an animation that allows the player to change the background colour. This works fine.

Now I am trying to add spots that animate over the top of this.

My method of doing this is using a frame-by-frame mask and apply it to a stationary object identical to the background that is coloured in the same way.

It used exactly the same code with different variables. If I disable the mask, I can colour the unmasked shape as if it were the background.

However when the mask is applied. The masked spots get coloured for the first frame. Then will no-longer change colour. I have tried forcing the colour change script per frame, but it does not work, but it also does not tell me that my spot background cannot be found. It throws up no errors what-so-ever.

Code is as follows.

import fl.controls.ColorPicker;
import fl.events.ColorPickerEvent;
import flash.geom.ColorTransform;
import flash.events.Event;

var spotscolor:ColorTransform = new ColorTransform();

var SpotsArray:Array=new Array();
SpotsArray.push(spots1);
for (var j:int=0;j<SpotsArray.length;j++)

stage.addEventListener(Event.ENTER_FRAME, colorChangerInitial2);

function colorChangerInitial2(event:Event):void{

    spotscolor.color = mcPanel.SpotPicker.selectedColor;
    for(var j:Object in SpotsArray) {
    SpotsArray[j].transform.colorTransform = spotscolor ;}

}

Definition com.greensock.TweenMax could not be found error

This is a sample project that I got from Google. It's a simple fortune wheel project. When I run this code. I get an error Definition com.greensock.TweenMax could not be found. I understand that the TweenMax path was not there in the project. I had downloaded the package from the TweenMax Website, and My question is how do I import the package to my project? Can Someone please help me. I'm new to flash programming.

package
{
import flash.display.Sprite;
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.events.Event;
import com.greensock.TweenMax;

public final class Main extends Sprite
{
    private var speed:Number = 0;
    private var paddles:Vector.<Sprite> = new Vector.<Sprite>();
    private var line:Shape;
    private var lastPaddle:String;

    public final function Main():void
    {
        paddles.push(wheel.p1, wheel.p2, wheel.p3, wheel.p4, wheel.p5, wheel.p6, wheel.p7, wheel.p8, wheel.p9, wheel.p10);
        listeners('add');
    }

    private final function listeners(action:String):void
    {
        if(action == 'add')
        {
            stage.addEventListener(MouseEvent.MOUSE_DOWN, startDraw);
            stage.addEventListener(MouseEvent.MOUSE_UP, spinWheel);
        }
        else
        {
            stage.removeEventListener(MouseEvent.MOUSE_DOWN, startDraw);
            stage.removeEventListener(MouseEvent.MOUSE_UP, spinWheel);
        }
    }

    private final function startDraw(e:MouseEvent):void
    {
        line = new Shape();
        addChild(line);

        line.graphics.moveTo(mouseX, mouseY);
        line.graphics.lineStyle(8, 0x000000, 0.3);
        stage.addEventListener(MouseEvent.MOUSE_MOVE, drawLine);
    }

    private final function drawLine(e:MouseEvent):void
    {
        line.graphics.lineTo(mouseX, mouseY);
    }

    private final function spinWheel(e:MouseEvent):void
    {
        stage.removeEventListener(MouseEvent.MOUSE_MOVE, drawLine);
        listeners('rm');

        speed = line.height * 0.1;
        removeChild(line);
        line = null;

        stage.addEventListener(Event.ENTER_FRAME, spin);
    }

    private final function spin(e:Event):void
    {
        /* Rotate Wheel */

        wheel.rotationZ += speed;

        /* Detect Value */

        for(var i:int = 0; i < 10; i++)
        {
            if(indicator.hArea.hitTestObject(paddles[i]))
            {
                lastPaddle = paddles[i].name;
            }
        }

        /* Decrease speed */

        speed -= 0.1;

        /* Remove lIstener and reset speed when wheel stops */

        if(speed <= 0)
        {
            stage.removeEventListener(Event.ENTER_FRAME, spin);
            speed = 10;
            run(lastPaddle);
            listeners('add');
        }
    }

    function run(action:String):void
    {
        switch(action)
        {
            case 'p1':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xF15D5D, tintAmount:1}});
                break;
            case 'p2':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xC06CA8, tintAmount:1}});
                break;
            case 'p3':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x644D9B, tintAmount:1}});
                break;
            case 'p4':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x5E98C6, tintAmount:1}});
                break;
            case 'p5':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x4789C2, tintAmount:1}});
                break;
            case 'p6':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x55C4CB, tintAmount:1}});
                break;
            case 'p7':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x57BC80, tintAmount:1}});
                break;
            case 'p8':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0x90CC6C, tintAmount:1}});
            break;
            case 'p9':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xEBE666, tintAmount:1}});
            break;
            case 'p10':
                TweenMax.to(colorMC, 0.5, {colorTransform:{tint:0xF29C69, tintAmount:1}});
                break;
        }
    }
}

}