lundi 30 novembre 2015

PHP ActionScript Error

I write PHP and ActionScript and connect them but result error

Here is the ActionScript

var filepath:String;

if (_url.indexOf("http") != 0) filepath = "http://localhost/adaptasi/";
else filepath = "../scripts/";

var send_lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();

result_lv.onLoad = function(success:Boolean):Void {
   TextIsi1.text = result_lv;
}

send_lv.sendAndLoad(filepath + "morfologi.php", result_lv, "GET");

And here is the PHP

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "adaptasi";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM materi";
$result = mysqli_query($conn, $sql);

{
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

and the result is error: Error SELECT * FROM materi & onLoad= type Function

Have any idea's of getting a new audio file to play with every click of this lesson?

I am somewhat new to AS but still trying to learn and accomplish what seems like tough stuff. I will prevail!

The code below shows my progress so far. I have a UI Loader that has a series of thumbnails. With each click of the thumbnail a new SWF file loads... well I'm trying to get an external series of mp3 files to do the same through an XML file. So far, I've managed to just get one audio file to play with every click AND it play over the existing file.

I simply want to get a new one to play with each thumbnail AND stop the previous audio file from playing if/when the user clicks a new thumbnail.

Please assist if possible...help me see the errors of my way. A little overwhelmed.

var imagesXML:XML;
var xmlLoader: URLLoader = new URLLoader();
xmlLoader.addEventlistener(Event.COMPLETE, xmlLoaded);
xmlLoader.load(new URLRequest("lessons/images/Images5.xml"));
var thumbSounds:Dictionary = new Dictionary();


/////////////////////////////////////////////////////////////
////////////    thumbnail loader    /////////////////////////

var mySound:Sound;
var myChannel:SoundChannel;


function xmlLoaded(evt:Event):void
{
imagesXML = new XML(xmlloader.data);
var thumbLoader:UILoader;
for(var i:uint = 0; i < imagesXML.image.length(); i++)
    {
        thumbLoader UILoader(getChildByName("thumb" + 1));
        thumbLoader.load(new URLRequest("lessons/images/thumbs/" + imagesXML.image[i].@file));
        thumbLoader.buttonmode = true;
        thumbLoader.addEventListener(MouseEvent.CLICK, thumbClicked);
        var fullPath:String = "lessons/images/file-1.swf";
        mainLoader.load(new URLRequest(fullpath));
        thumbSounds[thumbLoader] = "lessons/audio/narration/ch1p" + thumbIndex + ".mp3";
    }
}



/////////////////////////////////////////////////////////////
////////////////   load Images  /////////////////////////////

function thumbClicked(evt:MouseEvent):void
{
    var thumbName:String = evt.currentTarget.name;
    var thumbIndex:uint = uint(thumbName.substr(5));
    var fullPath:String = "lessons/images/" + imagesXML.image[thumbIndex].@file;
    mainLoader.load(new URLRequest(fullPath));
    mySound.load(new URLRequest (thumbSounds[evt.currentTarget]));

//stop any sound playing
//  if (myChannel != null)
//  {
//  myChannel.stop();
//  }

// load mp3 file
//  mySound = new Sound(); myChannel = new SoundChannel();
//  mySound.load(new URLRequest ("lessons/audio/narration/ch1p3.mp3"));
//  mySound.play();
}

AS3: How do I access a variable from a parent object?

I'm new to AS3 and my code may look a bit off.

Basically, how my program works is that I have an instance of "Level" on the stage, and it is a MovieClip containing several other objects which are also MovieClips with their own document class. In the "Level" class, I can access the X and Y position from the instance of "Player", but in my "Arrow" class, which is also a child of Level, I'm unable to access the X and Y of "Player". What I tried to do is set a public static variable called playerX and playerY in the Level class and assign that to the player's x and y position every frame, and I try accessing the variable in the Arrow class by doing "var x:Number = Object(parent).playerX, I've also tried MovieClip(parent).playerX and parent.playerX and just player X, neither of them work.

So to sum it up, I need to access a variable from a parent class, but every way I have tried it just returns an error.

Sorry if this was a bit unclear, any help will be much appreciated!

How to set the visibility of a layer using a button

Right now I am trying to program a simple turn based fighting game in the vain of Pokemon but I have ran into a large problem; I have a fight button on the battle screen that when pressed should reveal two commands (Tackle and throw) but I am not sure how to get that to work

All help is appreciated.

air for android publishes apk never finish

I use native extensions for admob and in app billing in my air android aplication on flash cs6.. when ı publish apk publishing never finish no errors only being publishing.ı wait enough time to finish it but never finish.

ı think its reason app.xml file but ı cannot solve this problem.what is this problems reason please help

AS3 Linking-Loading Another Swf File

i made catching game and i have the swf file. In another flash project, i want to call that swf. I created a button and wrote the codes below.

btnn.addEventListener(MouseEvent.CLICK, fl_ClickToLoadUnloadSWF_4);

import fl.display.ProLoader;
var fl_ProLoader_4:ProLoader;


var fl_ToLoad_4:Boolean = true;

function fl_ClickToLoadUnloadSWF_4(event:MouseEvent):void
{
    if(fl_ToLoad_4)
    {
        fl_ProLoader_4 = new ProLoader();
        fl_ProLoader_4.load(new URLRequest("CathingGame.swf"));
        addChild(fl_ProLoader_4);
    }
    else
    {
        fl_ProLoader_4.unload();
        removeChild(fl_ProLoader_4);
        fl_ProLoader_4 = null;
    }

    fl_ToLoad_4 = !fl_ToLoad_4;
}

But when i click the button, i have the error below. What could be the possible solutions? I think i have this error because in the catching game, my fla and actionscript are in different file. I mean i use external .as file. Not in the fla file.

TypeError: Error #1009: Cannot access a property or method of a null object reference. at CatchingGame()

How can I launch a python script using Adobe AIR's NativeProcess?

I'm having more than a little trouble running a python script from an AIR application using the NativeProcess interface. In theory, this should be quite simple. Adobe even uses this as their example in the ActionScript 3.0 documentation for NativeProcess, as follows:

var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.py");
nativeProcessStartupInfo.executable = file;

They even include the contents of what test.py might include:

#!/usr/bin/python
# ------------------------------------------------------------------------------
# Sample Python script
# ------------------------------------------------------------------------------

import sys

for word in sys.argv: #echo the command line arguments
    print word

print "HI FROM PYTHON"
print "Enter user name" 
line = sys.stdin.readline()

sys.stdout.write("hello," + line)

The problem is that, as far as I can see, this simply doesn't work. I get the following error when I attempt it:

Error #3219: The NativeProcess could not be started. '%1 is not a valid Win32 application.

Presumably the latest version of AIR (19.0) doesn't allow the execution of anything without an "exe" file extension. The following code does seem to do what I want:

var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = new File("C:/Python/Python35/python.exe");
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.applicationDirectory.resolvePath(".");

var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "test.py";
nativeProcessStartupInfo.arguments = processArgs;

The problem here is twofold. First, you need to know the absolute path to the executable, which I can't assume. Second, the code is no longer platform independent. The file extension would be something else on Linux or Mac.

I thought I might solve the first problem by requiring a %PYTHON_PATH% environment variable and then making the executable dependent on that. However, I can't figure out a way to use an environment variable within the ActionScript File object. It "helpfully" escapes all the "%" characters before ever sending something to the command line.

At this point this fairly simple problem has turned into a showstopper. Could someone help me understand a way to either:

  1. Execute something with the "py" extension with NativeProcess
  2. Successfully resolve a path that depends on an environment variable in the File object?

Flex - corner is not working properly

I am using numeric stepper to give the corner and weight of rectangle.

<fx:Script>
<![CDATA[
    protected function weight_changeHandler(event:Event):void
    {
        borderStroke.weight = wght.value;
    }           
    protected function corner_changeHandler(event:Event):void
    {
        border.topLeftRadiusX= border.bottomLeftRadiusX =border.topRightRadiusX=border.bottomRightRadiusX=corner.value;
    }           
]]>
</fx:Script>

<s:layout >
    <s:VerticalLayout paddingLeft="50" paddingTop="50"/>
</s:layout>
<s:Rect horizontalCenter="0" verticalCenter="0" height="300" width="300"     id="border">
    <s:stroke>
        <s:SolidColorStroke id="borderStroke" color="#000000" joints="miter"  caps="square" weight="1" alpha="1"/>
    </s:stroke>
</s:Rect>
<s:NumericStepper id="wght" change="weight_changeHandler(event)" maximum="100"/>
<s:NumericStepper id="corner" change="corner_changeHandler(event)" maximum="100"/>

corner and weight working fine separately. Now I am giving maximum value 100 to weight and the minimum value 0 to corer. The output will be like

enter image description here

when I am trying to increase the corner to 1, it's working like

enter image description here

I am giving the corner value as 1. But the rectangle corner looking like more than 50. I don't know what is the problem.

Anybody can find my mistake?

Thank you

dimanche 29 novembre 2015

removeChild() on parent will remove his child?

I have construction that below:

parent
   + child
   + child
   + child
   + sub-parent
         + sub-child
         + sub-child

For now, I use multiply of "removeChild()", to remove elements from scene one by one. Like that:

removeChild(sub-child);
removeChild(sub-child);
removeChild(sub-parent);
//and so on 

It's okay, but i found out that if I remove parent all his children will disappear from scene too. (but for now i do not know for sure ...)

So my question is quite simple:

How to remove elements from scene in correct way ? As I do now (one by one) or I could remove just a parent and my code will be a little bit shorter. Or it's same thing ?

Thanks in advance!

Actionscript, hasOwnProperty() of multidimensional arrays

I'm trying to check wether a key exists in a multidimensional array. The following code is my example:

var tiles:Array = new Array(
                    new Array(4),
                    new Array(4),
                    new Array(4),
                    new Array(4)
                 );
if(test.hasOwnProperty(2)) {
  trace('True');
} else {
  trace('False');

This returns True, as expected since the key 2 indeed exists in the array "test".

However if I try to this on any of the arrays within my array, the code always returns False.

var tiles:Array = new Array(
                    new Array(4),
                    new Array(4),
                    new Array(4),
                    new Array(4)
                 );
if(test[1].hasOwnProperty(2)) {
  trace('True');
} else {
  trace('False');

I was hoping anyone could shed some light on this, what am I missing? Maybe there is another way of doing this check? Any help is much appreciated, thanks! :)

Removing items of an array from stage in as3- one each time

I am trying to remove movieclips of an array from the stage. I want to remove one item of the circles array every time there is a click in an item from the square array. I wrote this code but something is missing and i can not figure it out because all the items of the circles array disappear from stage with the first click. Can you please help me.

var circles:Array = [circle1, circle2, circle3, circle4,circle5, circle6];
var counter:int = 0; 


var square:Array = new Array   (square1,square2,square3,square4,square5,square6,square7,square8,square9,square10,square11,square12,square13,square14,square15,square16,square17,square18,square19,square20,square21);
  for(var i:int = 0; i < square.length; i++)
{
    square[i].addEventListener(MouseEvent.CLICK, clickTomove);
    function clickTomove(e:MouseEvent):void
{
    trace("square");
    var len:int=circles.length;
    for(var o:int=0; o<circles.length; o++)
    this.removeChild(circles[o]); 
    circles.splice(o,1);
}
}

Allow a button press by true or false variable AS3

I have been making an advent calendar in which when you press the button the door opens. I have created a variable to control which date you can open them on called 'AllowOpen' if it is the right date. I have also created a function to go to a frame when clicked.

var AllowOpen: Boolean = false;
if (Day == 1) {
    AllowOpen = true;
} else {
    AllowOpen = false;
}

button1.addEventListener(MouseEvent.MOUSE_DOWN, click);

function click(event:MouseEvent):void
{
    gotoAndStop(2)
}

I can't work out how I would tell the the program to only open the door if allow open is true. I have tried the 'if' statement but it doesn't seem to work. Thanks

Is anyone interested in looking at my code for a game? I'm getting strange errors

I'm trying to make my first real, simple shooter game. I've read through tutorials online and instead of directly copying code, I tried to take things the next level to actually understand the code and add my own twists. With this in mind, I've recently been learning arrays and not sure if I am using them correctly.

I'm getting strange, intermittent

Error #2025 DisplayObject must be a child of the caller

messages in the output window, not the compiler window.

So, I don't know what line of code is generating this problem. By commenting out blocks of code I have narrowed it down to the modules labeled "CLEANUP MISSED ENEMIES" and "BULLET RATE OF SHOOTING", but the 'why' is beyond my understanding.

I am sure there will be many great comments pointing out conventions I get wrong and errors I am making. I value every chance to learn so please give your input as you see fit! I bet there are way better methods to do the things I am doing!

package{

import flash.events.Event;
import flash.display.MovieClip;
import flash.media.Sound;
import flash.media.SoundChannel;
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import fl.motion.Color;
import flash.display.DisplayObject;

public class chopper extends MovieClip{
public function chopper(){
    boot();
}
public function boot():void{

/////////VARS
var coptr:MovieClip = new copter();
var bulit:MovieClip = new bullit();
var mouseIsDn = false;
var speed = 0;
var PEW = false
var meter:MovieClip = new meters();

var bltArray:Array = new Array();

var airArray:Array = new Array();
var gndArray:Array = new Array();

var gameTIMERa:Timer = new Timer(5000);
var gameTIMERb:Timer = new Timer(10000);

stage.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
stage.addEventListener(MouseEvent.MOUSE_UP, unclicked);

function clicked(e:Event):void{
    mouseIsDn = true;
}
function unclicked(e:Event):void{
    mouseIsDn = false;
}

/////////INTRO SCREEN
var titl:MovieClip = new title();
addChild(titl);
var strt:MovieClip = new start();
addChild(strt);
var govr:MovieClip = new gOVER();

var ctINTRO:Color = new Color();
ctINTRO.setTint(Math.random()*0xFFFFFF, 0.5);
BG.transform.colorTransform = ctINTRO;

/////////MUSIC
var ChanAB:SoundChannel = new SoundChannel();
var Amusic:Sound = new musicA();
var Bmusic:Sound = new musicB();
ChanAB = Amusic.play(0, 9999);

/////////SFx
var ChanSFx:SoundChannel = new SoundChannel();
var Ashoot:Sound = new shootA();

var SFx:Array = new Array();
var Asuck:Sound = new suckA();
SFx.push(Asuck);
var Bsuck:Sound = new suckB();
SFx.push(Bsuck);
var Csuck:Sound = new suckC();
SFx.push(Csuck);

var gOver:Sound = new over();

/////////START
strt.startBTN.addEventListener(MouseEvent.CLICK, str);
function str(e:Event):void{
    removeChild(titl);
    removeChild(strt);
    ChanAB.stop();
    BG.transform.colorTransform = new ColorTransform;
    ////////////
    ChanAB = Bmusic.play(0, 9999);
    addChild(coptr);
    TweenLite.to(coptr, 3, {x:157, y:316});
    addChild(meter);
    meter.x = 861;
    meter.y = 9;
    TweenLite.to(meter, 1, {x:735});
    meter.life.gotoAndPlay(2);
    gameTIMERa.addEventListener(TimerEvent.TIMER, addAIR);
    gameTIMERa.start();
    gameTIMERb.addEventListener(TimerEvent.TIMER, addGND);
    gameTIMERb.start();
}

/////////ADDING ENEMIES
function addAIR(e:TimerEvent):void{
    var Aair:MovieClip = new airA();
    Aair.x = 805;
    Aair.scaleX = .25
    Aair.y = Math.random() * stage.stageHeight - Aair.height;
    Aair.scaleY = .25
    airArray.push(Aair);
    addChild(Aair);
}

function addGND(e:TimerEvent):void{
    var Agnd:MovieClip = new gndA();
    Agnd.x = 805;
    Agnd.scaleX = .25
    Agnd.y = 430 + Math.floor(Math.random() * 36);
    Agnd.scaleY = .25
    gndArray.push(Agnd);
    addChild(Agnd);
}



addEventListener(Event.ENTER_FRAME, startLoop);
function startLoop(e:Event):void{
    if(coptr.x == 157 && coptr.y == 316){
        speed = 10;
        meter.life.gotoAndStop(10);
        removeEventListener(Event.ENTER_FRAME, startLoop);
        addEventListener(Event.ENTER_FRAME, gameLoop);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, shoot);
    }
}

/////////COPTER SHOOTING
function shoot(e:Event):void{
    if(PEW == false){
        ChanSFx = Ashoot.play();
        bulit.x = coptr.x + 5;
        bulit.y = coptr.y;
        bltArray.push(bulit);
        addChild(bulit);
        PEW = true;
    }
}

/////////LIFE METER
function lifeMeterA(e:Event = null):void{
    if(meter.life.width > 59){
        meter.life.scaleX -= .04;
    }
    else if(meter.life.width < 59 && meter.life.width > 29){
        meter.life.gotoAndStop(11);
        meter.life.scaleX -= .04;
    }
    else if(meter.life.width < 29 && meter.life.width > 15){
        meter.life.gotoAndStop(12)
        meter.life.scaleX -= .04;
    }
    else if(meter.life.width < 15 && meter.life.width > 1.5){
        meter.life.gotoAndPlay(2);
        meter.life.scaleX -= .04;
    }
}
function lifeMeterB(e:Event = null):void{
    if(meter.life.width > 59){
        meter.life.scaleX -= .01;
    }
    else if(meter.life.width < 59 && meter.life.width > 29){
        meter.life.gotoAndStop(11);
        meter.life.scaleX -= .01;
    }
    else if(meter.life.width < 29 && meter.life.width > 15){
        meter.life.gotoAndStop(12)
        meter.life.scaleX -= .01;
    }
    else if(meter.life.width < 15 && meter.life.width > 1.5){
        meter.life.gotoAndPlay(2);
        meter.life.scaleX -= .01;
    }
}

////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////MAIN LOOP
function gameLoop(e:Event) {
    ////////////////////////COPTER MOVEMENT
    trace(bltArray);
    trace(airArray);
    trace(gndArray);
    coptr.y += speed;
    if(mouseIsDn){
        if(speed > -5){
            speed -= 1;
        }
    }else{
        if(speed < 10){
            speed += .25;
        }
    }

    ////////////////////////BULLET MOVEMENT
    if(bulit){
        bulit.x += 10;
    }


    if(coptr.y > stage.stageHeight - coptr.height*.5){
        coptr.y = stage.stageHeight - coptr.height*.5;
    }
    else if(coptr.y < 0 + coptr.height*.5){
        coptr.y = 0 + coptr.height*.5;
    }

    ////////////////////////COLLISIONS
    for(var i = 0; i<numChildren; i++){
        if(getChildAt(i) is airA){
            var b = getChildAt(i) as airA;
            if(b.hitTestObject(coptr)){
                lifeMeterA();
            }
            if(b.hitTestObject(bulit)){
                airArray.shift();
                removeChild(b);
                removeChild(bltArray[0]);
                PEW = false;
                var m:uint = uint(Math.random() * 3);
                ChanSFx = SFx[m].play();
            }
        }
        else if(getChildAt(i) is gndA){
            var c = getChildAt(i) as gndA;
            if(c.hitTestObject(coptr)){
                lifeMeterB();
            }
            if(c.hitTestObject(bulit)){
                gndArray.shift();
                removeChild(c);
                removeChild(bltArray[0]);
                PEW = false;
                var n:uint = uint(Math.random() * 3);
                ChanSFx = SFx[n].play();
            }
        }
    }
    if(coptr.y > stage.stageHeight - coptr.height){
        lifeMeterA();
    }

    ////////////////////////CLEANUP MISSED ENEMIES
    if(airArray[0] && airArray[0].x < 0){
        airArray.shift();
    }

    if(gndArray[0] && gndArray[0].x < 0){
        gndArray.shift();
    }

    ////////////////////////BULLET RATE OF SHOOTING
    if(bltArray[0] && bltArray[0].x > stage.stageWidth){
        PEW = false;
        bltArray.shift();
    }

    ////////////////////////END GAME
    if(meter.life.width < 1.5){
        removeEventListener(Event.ENTER_FRAME, gameLoop);
        gameTIMERa.stop();
        gameTIMERb.stop();
        meter.life.gotoAndStop(13);
        TweenLite.to(meter, .5, {x:861});
        gameO();
    }
}

function gameO(e:Event = null):void{
    addChild(govr);
    govr.x = 0;
    govr.y = 0;
    ChanAB.stop();
    ChanSFx = gOver.play();
    ChanSFx.addEventListener(Event.SOUND_COMPLETE, restart);
}
function restart(e:Event):void{
    removeChild(govr);
    removeChild(coptr);
    boot();
}
}
}
}

Thanks in advance!

ActionScript 3 vCam Dithering Bug

I'm creating a small RPG game and everything was going well until I tried to set up the vCam in a class. It was working well when everything, the level, the vCam and the player were all in main, but now that the level is in it's own class, the vCam is acting up.

Normally, it just follows the player. It still does that but now, whenever I move the player it dithers, leaving a weird path behind it. The player is the green square. (See image below)

What the Bug Looks Like

Also, the hitboxes stop working as well, all because I added a camera.

Does anyone know why this is happening? I got the vCam code online because I have no idea how to work with cameras in AS3.

The vCam code works by adding it to the stage as a primitive shape. The smaller it is, the more it zooms in, the larger it is the more it zooms out.

My code it here:

vCam Code

Level Code

How to turn a shape into a button AS3

I have started making an advent calendar using the adobe flash professional software. I have drawn each 'door' individually with the draw tool on separate layers. I need to know how to use action script to wait for a click on one of the doors and then goto a specific layer and stop. I have tried different methods such as

button.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);

but it throws up errors. Any ideas would be appreciated. Thanks

actionscript 3 :error. type coercion failed

I am getting following error when trying to simulate CalendarLayoutChangeEvent on a DateField object.

cannot convert mx.events::CalendarLayoutChangeEvent@feb667 to mx.events.CalendarLayoutChangeEvent

I am dispatching events on swf's which are loaded at runtime.

any help will be appreciated.

private function setDateField(child:Object, dateString:String):String
{                   
    child.selectedDate = compileDateValue(dateString,child.formatString);
    var changeEvent:CalendarLayoutChangeEvent = new CalendarLayoutChangeEvent("change", true, false, null, new Event("change"));
    var retval:String;
    try
    {
        retval = String(child.dispatchEvent(changeEvent));
    }
    catch(e:Error)
    {   
        trace(e);
    }
    return retval;
}

samedi 28 novembre 2015

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

I have no idea what is causing the error. I'm sure its very obvious. (See comment in FloorTile).

package src.main{

    import src.tilespack.Tile;

    public class Main{

        public var tile:Tile;

        public function Main{
            var t:Tile = Tile.tiles[0]; //Error caused by this line
        }

Tile:

package src.tilespack{

    public static var tiles:Array = [];

    public static var floorTile:Tile = new FloorTile(0);

    public var bitmapData:BitmapData;

    public function Tile(bitmapData:BitmapData, ID:int)
    {
        this.ID = ID;
        tiles[ID] = this;
        this.bitmapData = bitmapData;
    }

}

FloorTile:

package src.tilespack{
    import src.gfx.Assets;
    import src.tilespack.Tile;

    public class FloorTile extends Tile{ //Error here

        public function FloorTile(ID:int){
            super(Assets.floorTileData, ID);
        }
    }
}

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

Tile List Action Script 3

I was creating a tile list, then I add some items and scroll bar. The problem is, the item doesn't fill all the space ,there is leftover space, How I can fill all the item picture to item space ?.

thanks

Issues wih BitmapData.hitTest with rotated MovieClips

I've been having a lot of trouble with collision testing in as3. I sort of figured out how to handle the BitmapData.hitTest() function along with the matrix stuff to handle rotated movieclips, but for some objects it still doesn't work.

I'm trying to make a game where you shoot targets. I have a class called Portal, which has an attribute called partnerPortal, which is another portal. When the ammo hits the receptor of the portal, a little rectangular MovieClip at the back of the opening, the ammo's x and y simply get reassigned to the partnerPortal's x and y (with some additions to make it look right). When it hits anywhere else, it calls ammo's selfDestruct function.

Link to an image of the portal and receptor: http://ift.tt/1MLyqPd

Here's the code for collision detection:

    public function adjustMatrix(transformer:HitObject):void {
        var hitRect = transformer.getBounds(this);
        var hitMatrix = transformer.transform.matrix;
        var xOffset:Number = transformer.x - hitRect.x
        var yOffset:Number = transformer.y - hitRect.y
        hitMatrix.tx = 0;
        hitMatrix.ty = 0;
        hitMatrix.translate(xOffset, yOffset);
        var hitMap = new BitmapData(hitRect.width, hitRect.height, true, 0);
        hitMap.draw(transformer, hitMatrix);
    }

    public function checkStrike(ammo:Ammo):void {
        for(var i = 0; i <= hitObjects.length - 1; i++) {
            var hitObject = hitObjects[i];              
            if (hitObject.hitTestObject(ammo)) {
                trace("box " + hitObject); // Sees if the ammo has hit the bounding box
                adjustMatrix(ammo);
                var ammoPoint:Point = new Point(ammo.hitRect.x, ammo.hitRect.y);
                var hitPoint:Point = new Point(hitObject.hitRect.x, hitObject.y);
                if (hitObject.hitMap.hitTest(hitPoint, 1, ammo.hitMap, ammoPoint, 1)) {
                    hitObject.hit(ammo); // calls the portal's (or whatever else the ammo hits) hit function
                }
            }
        }

And for the portal's hit function:

    public function hit(ammo:Ammo):void {
        trace(ammo.y,  this.y, ammo.x, this.x);
        if (receptor.hitTestObject(ammo)){
            adjustPosition(ammo); // Aligns the ammo so it looks like it is emerging from the portal
        }
        else{
            ammo.selfDestruct(this);
        }
    }

The default portal is facing upwards, and the rotation value for each instance is stored in a JSON file. For the up and right instances, they work fine. For the left and down instances it starts to break. When a portal is facing left, the ammo hits the bounding box when it hits the portal, but it moves right over it and doesn't interact. When facing up, the portal calls the selfDestruct funtion when the ammo reaches the opening, not the receptor.

ArrayCollection: filterFuntion with multiple filter functions

I search an idea to filter an area collection with 2 criteria. Do you know how to do that easily.

Thanks for helping.

Best regards

Moving Objects in Flash CC 2015 actionscript is not working but the codes show no error

I'm pretty new to Flash code so I'm kinda struggling applying it to my project

I have all the codes right (maybe the x and y are a bit off but it's still fine, I can fix it later),however none of my objects move. I tried to rewrite just start with 1 line and even make a fresh document but they did not work for me. So I'm trying to get help from any of you here. here's the file that I have http://ift.tt/1NfGftj with all of the assets, dev file, deploy files. Please take a look and explain to me what happened to my codes/ file. Sorry for the vague explaination since I'm an international student, I might have troubles expressing the problems. Thanks everyone again :)

AS3 - Access Property of Class in different package

I have a problem with accessing properties from different packages. I can't access any properties of the Assets class from the FloorTile Class. How do I get floorTileData from Assets?

Assets:

package src.gfx{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

    public class Assets{
        public var floorTileData:BitmapData = new BitmapData(0, 0); 

        //Other Code

    }

}

FloorTile:

package src.tilespack{
import src.gfx.Assets;

    public class FloorTile extends Tile{

        public function FloorTile(ID:int){
            super(Assets.floorTileData, ID); //Error in this line
        }
    }
}

The error is due to this line

super(Assets.floorTileData, ID);

I get the Error - 1119: Access of possibly undefined property floorTileData through a reference with static type Class.

Is it possible to make use of a value returned from a method called by a delegate?

While experimenting with a basic coding stuff, I wondered, if a value returned by a method called by a delegate, could be used or captured. In other words, where will the return value will go ?

For example :

class Main extends Sprite
{
   public var mc:MyMc;

   function Main()
  {
      mc.addEventListener( "myClick" , myClick);

  }

  function myClick(e:Event):String  //returning a string 
  {
     return "What happens to this return value ???" 
  }


}



class MyMc extends MovieClip
{

   function MyMc()
  {
      addEventListener( MouseEvent.CLICK , onClick);

  }

  function onClick(e:Event):String  //returning a string 
  {
     dispatchEvent(new Event("myClick")); 
  }


}

Wifi Direct Group Owner & discovering neighbors

If I create a Wifi-Direct group on Android using AIR Native Extension, devices that connect to that network can discover each other utilizing NetConnection, NetGroup etc. The problem is that Group Owner itself is not discovered and thus not added so it can't communicate with peers connected to it. The interesting thing is that if this Group Owner is already connected to another wifi AP, then it is discovered too and it can communicate with other peers. This connection keeps even after GO disconnects from that AP so I think the only problem is initial peers discovery. I can also use sockets to establish connection between GO and a wifi device connected to its group but I really need to use NetGroup and its advantages (RTMFP, Multicasting etc.).

So - anyone has an idea how to establish a NetGroup where Wifi-Direct GO and its clients can see each other without help of any other AP?

Thank you!

AS3 Error 1084 - expecting rightbrace before end of program

I am new to action script an I can't work out why I am getting these errors.

Error 1084 - expecting rightbrace before end of program

This is all the code that is on the layer the error states. I have read other places that if you have not used the braces correctly you get this error however I have not used them at all.

import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Sprite
stop();

Any help would be greatly appreciated! Thanks

how to send message from flash to javascript

I have a HTML page that it has an flash(swf) file. in flash file, I have a radio button. I want to call a javascript(or jquery) function when flash radio button is selected. is this possible? if yes how?

vendredi 27 novembre 2015

how to set min an max width to anchor popup in flex?

if(anchorWidthFlag)
{
popUp.popUpWidthMatchesAnchorWidth = false;
popUp.explicitWidth = anchorWidth;
}

here AnchorWidthFlag = true and anchorWidth = 350;

i tried this way

1) popUpWidthMatchesAnchorWidth = false
2) explicitWidth = anchorWidth //350

but not get appropriate output.

this image show the output of above code.

i want to set minWidth to anchor popup, can anyone help me?

flashdevelop error while loading initial content

I have been struggling with this stupid error from couple of hours. Have tried everything but it still persists. I'm unable to run any Flash Mobile AS3 project in FlashDevelop.

This is what it says in Output panel:

Debugger startup error. For troubleshooting see: http://ift.tt/1rEtkKX
Error details: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
   at net.sf.jni4net.jni.JNI.Dll.JNI_GetDefaultJavaVMInitArgs(JavaVMInitArgs* args)
   at net.sf.jni4net.jni.JNI.Init()
   at net.sf.jni4net.jni.JNI.CreateJavaVM(JavaVM& jvm, JNIEnv& env, Boolean attachIfExists, String[] options)
   at net.sf.jni4net.Bridge.CreateJVM()
   at net.sf.jni4net.Bridge.CreateJVM(BridgeSetup setup)
   at FlashDebugger.DebuggerManager.Start(Boolean alwaysStart)
[Capturing traces with FDB]

and this is what it shows in the console/command prompt:

error while loading initial content

Please if anyone had seen this error and solved it successfully, I would really appreciate any help.

Thanks!

enter image description here

How can be a ArrayCollection created?

There is a nice example of Advanced Datagrid and use of ArrayCollection here. I like to have something like that;

private var dpFlat:ArrayCollection = new ArrayCollection([
{Region:"Southwest", Territory:"Arizona", 
  Territory_Rep:"Barbara Jennings", Actual:38865, Estimate:40000}, 
{Region:"Southwest", Territory:"Arizona", 
  Territory_Rep:"Dana Binn", Actual:29885, Estimate:30000},  
{Region:"Southwest", Territory:"Central California", 
  Territory_Rep:"Joe Smith", Actual:29134, Estimate:30000},  
{Region:"Southwest", Territory:"Nevada", 
  Territory_Rep:"Bethany Pittman", Actual:52888, Estimate:45000},  
{Region:"Southwest", Territory:"Northern California", 
  Territory_Rep:"Lauren Ipsum", Actual:38805, Estimate:40000}, 
{Region:"Southwest", Territory:"Northern California", 
  Territory_Rep:"T.R. Smith", Actual:55498, Estimate:40000},  
{Region:"Southwest", Territory:"Southern California", 
  Territory_Rep:"Alice Treu", Actual:44985, Estimate:45000}, 
{Region:"Southwest", Territory:"Southern California", 
  Territory_Rep:"Jane Grove", Actual:44913, Estimate:45000}
]);

I need to read an XML file and get some attributes from it. Then create a custom ArrayCollection with these attributes. Right now I am creating a custom XML but I no longer want to use XML and instead check Array Collection.

Here is the code I read and create another XML;

kitapKonuSayisi = _tempXMLOR.Body.Ogrenci.length();

for(var itra:int = 0; itra < kitapKonuSayisi; itra++)
{
    uniteAdi = _tempXMLOR.Body.Ogrenci[itra].UniteAdi;
    konuAdi  = _tempXMLOR.Body.Ogrenci[itra].KonuAdi;
    ogrenciAyrintiRaporArray.push([uniteAdi, konuAdi]);
}

for(var itrc:int = 0; itrc < kitapKonuSayisi; itrc++)
{
    kitapUniteSayisi = _tempXMLOR.Body.Ogrenci[itrc].UniteAdi.length();
    uniteAdi = _tempXMLOR.Body.Ogrenci[itrc].UniteAdi;
    if(raporStringUnitCheck === true)
    {
        ogrenciAyrintiRaporStr += ('\t<Unite name="' + uniteAdi + '" yuzde="' + 100 + '">\n');
        raporStringUnitCheck = false;
    }

    for(var itrd:int = 0; itrd < kitapUniteSayisi; itrd++)
    {
        if(ogrenciAyrintiRaporArray[itrd][0] == _tempXMLOR.Body.Ogrenci[itrc].UniteAdi)
        {
            konuAdi = _tempXMLOR.Body.Ogrenci[itrc].KonuAdi;
            ogrenciAyrintiRaporStr += ('\t\t<Konu name="' + konuAdi + '" yuzde="' + 100 + '"/>\n');
        }
    }
}
if(raporStringUnitCheck === false && raporStringCompCheck === false)
{
    ogrenciAyrintiRaporStr += ('\t</Unite>\n');
    ogrenciAyrintiRaporStr += ('</Rapor>');
    raporStringCompCheck = true;
    raporString2XML = new XML(ogrenciAyrintiRaporStr);
}

So how can I create ArrayCollection and populate elements in that scheme?

Playerio listRooms() issue (as3 client)

Using PlayerIO for my first time, so maybe I've done an obvious mistake, but I realy don't understand what it could be.

On listRoom's callback there is unhandled error, causing crash.

code:

client.multiplayer.listRooms(gameType, {}, limit, offset, onLoaded, errorHandler);

gameType - is valid, callbacks are not null.

Error is hidden in swc, so it is difficult to analyse it.

Stack:

Function/<anonymous> at C:\builddir\Client Libraries\ActionScript 3\PlayerIOClient\src\playerio\generated\Multiplayer.as:58
Function/<anonymous> at C:\builddir\Client Libraries\ActionScript 3\PlayerIOClient\src\playerio\utils\HTTPChannel.as:54
flash.events::EventDispatcher/dispatchEventFunction
flash.events::EventDispatcher/dispatchEvent
flash.net::URLLoader/onComplete

Output: [Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference.

Thanks for any help and sorry for my English

SolidColorStroke - caps property is not working

I am trying to set corner and weight for a rectangle

<fx:Script>
    <![CDATA[
        protected function weight_changeHandler(event:Event):void
        {
            borderStroke.weight = wght.value;
        }           
        protected function corner_changeHandler(event:Event):void
        {
            border.topLeftRadiusX= border.bottomLeftRadiusX =border.topRightRadiusX=border.bottomRightRadiusX=corner.value;
        }           
    ]]>
</fx:Script>

<s:layout >
    <s:VerticalLayout paddingLeft="50" paddingTop="50"/>
</s:layout>
<s:Rect horizontalCenter="0" verticalCenter="0" height="300" width="300" id="border">
    <s:stroke>
        <s:SolidColorStroke id="borderStroke" color="#000000" caps="square" weight="1" alpha="1"/>
    </s:stroke>
</s:Rect>
<s:NumericStepper id="wght" change="weight_changeHandler(event)" maximum="100"/>
<s:NumericStepper id="corner" change="corner_changeHandler(event)" maximum="100"/>

when I am increasing the weight, the rect corner also changing. I am getting like this enter image description here

Anybody can tell me what I missed? what is my mistake?

Smooth image on load in as3

I am new here and a complete noob when it comes to as3. Somehow I have managed to put this together with some help from different places. And now I turn to you guys :)

I need to put smoothing on my images and thumbs that Im loading from an XML file. I have tried a lot of things but can't get any of it to work and I get this error: Scene 1, Layer 'as3', Frame 1, Line 27 1120: Access of undefined property e. -> So I know var bitmapContent:Bitmap = Bitmap( e.target.content ); is the problem. but I have no idea what to use instead of e. I this i what I have so far:

import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.None;
import flash.display.Bitmap;


// Loads the first image//
var i =new Loader();
i.load(new URLRequest("images/1.jpg"));
mainLoader.addChild(i)


//Loads the XML file//
var picsXML:XML;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE ,  xmlLoaded);
xmlLoader.load(new URLRequest("imagelist.xml"));


//Loads images into thumbs//
function xmlLoaded(event:Event):void{
    picsXML = new XML(xmlLoader.data);
    //trace(picsXML);
    var bitmapContent:Bitmap = Bitmap( e.target.content );
    bitmapContent.smoothing = true;
    var thumbLoader:UILoader;
    for (var i:uint=0; i<picsXML.image.length(); i++)

    {
        thumbLoader=UILoader(getChildByName("thumb"+i));
        thumbLoader.load(new URLRequest("thumbs/"+picsXML.image[i].@file));
        thumbLoader.buttonMode = true;
        thumbLoader.addEventListener(MouseEvent.CLICK, thumbClicked);
        thumbLoader.addEventListener(MouseEvent.CLICK, tester); 
    }
}

//Loads large image when thumb is clicked//
function thumbClicked(event:MouseEvent){
    //var bitmapImage:Bitmap = event.target.content;
    //bitmapImage.smoothing = true;
    var thumbName:String = event.currentTarget.name;
    var thumbIndex:uint = uint(thumbName.substr(5));
    var fullPath:String = "images/"+picsXML.image[thumbIndex].@file;
    mainLoader.load(new URLRequest(fullPath));
    var myTween:Tween = new Tween(mainLoader,"alpha", None.easeNone, .3,1,18,false);

}

//Removes the first image when thumbs is clicked//
function tester(event:MouseEvent){
    if (mainLoader.contains(i)) {
        trace("hej")
     mainLoader.removeChild(i);
    }
    }

hello how to set minWidth and maxWidth to anchor popup, I tried MatchesAnchorWidth = "false" but it set width according to Data

public function filterData():void
    {

        if(!this.focusManager || this.focusManager.getFocus() != inputTxt)
            return;

        if(!popUp)
            return;

        if(isFilterFunctionEnabled)
            collection.filterFunction = filterFunction;

        var customSort:Sort = new Sort();
        customSort.compareFunction = sortFunction;
        collection.sort = customSort;
        collection.refresh();

        if((text == "" || collection.length == 0) && !_forceOpen)
        {
            popUp.displayPopUp = false;
        }
        else
        {
            popUp.displayPopUp = true;
            if(requireSelection)
                list.selectedIndex = 0;
            else
                list.selectedIndex = -1;

            callLater(setListProperties);
            list.height = Math.min(maxRows, collection.length) * 22 + 15;

            if(anchorWidth)
            {
                popUp.popUpWidthMatchesAnchorWidth = false;
                popUp.explicitWidth = anchorWidth;
            }
            else
                popUp.width = inputTxt.width;
        }
    }

this filter function i have use Anchor property popUpWidthMatchesAnchorWidth to set Dynamic width but i want to set minWidth and maxWidth to popup because of popup goes outside to component.

jeudi 26 novembre 2015

Flash AS3 | Looping sound for each animation set

with University done I've finally had time to go back to practicing my Flash work, and I need some help with getting sound to loop and change depending on what part of the animation is playing.

This is also partly a follow up question to an older one I asked, so look here to get more detail as to where I'm coming from if you don't understand! (I've solved that issue, the current one relates to following up on it!)

Flash AS3 | Finishing current animation set before code is executed

The situation is basic: I have two different scenes, one of a man walking and one of a man running. It loops seamlessly of the man walking until you hit a button, where it finishes the animation then starts looping the run animation. Likewise, hitting the button again, finishes the loop before going back to the looping walk animation. The code for the button is below.

  import flash.events.MouseEvent;


    Next2.addEventListener(MouseEvent.CLICK, Change_2);

function Change_2(event: MouseEvent): void

{
    addEventListener(Event.ENTER_FRAME, enterFrame);
    function enterFrame(e:Event):void {
    if (currentFrame == 30) {
        gotoAndPlay(31);
        removeEventListener(Event.ENTER_FRAME, enterFrame);
    }

}
}

My issue is trying to get a footstep sound to match up with these animations. So while the man is walking, the 'walking footsteps' sound clip will play and loop alongside the animation, and when the button is pushed and the animation moves into the running animation, the 'running footsteps'' sound will play.

Any help on this would be much appreciated. I'm terrible when it comes to anything audio/code based.

Faults when embedding images in Flash Develope

If I include an embed thingy, it gives a fault when I click Test Project, but works if I click it again. If I add another embed I have to click it twice (with faults each time) and it works on the third try.

This is the code I've been using to embed images:

[Embed(source = "../img/bluebg.png")]
    [Bindable]
    public var Bg:Class;
    public var bg:DisplayObject = new Bg();

It wasn't working at all, and started working (as it is now) when I added the [Bindable], although now it seems to work when I take it away.

The fault it gives is: [Fault] exception, information=ReferenceError: Error #1065: Variable FlexVersion is not defined.

Error #2048: Security sandbox violation: cannot load data from

I found an issue in my AS3 application. On my local machine everything is good, but when I sent it to my friend, he wasn't able to open it on his computer, because he got

Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: cannot load data from data.json

The same error happens when I upload my application to web. I can't play it and get the same error.

Here is my code:

var myTextLoader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("data.json");
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
myTextLoader.load(request);

...

private function onLoaded(e:Event):void 
{
            var loader:URLLoader = URLLoader(e.target);
            var myObject:Object = JSON.parse(loader.data);
}

How can I fix it? Please, help me if you can :)

how to use .visible properties in as3?

I just want to make some objects visible="false". But I can't. I can make some objects invisible, however it is not working for the objects in the array. Here is my codes. When score=3, objects should be invisible. It is a catching game. I use Adobe Flash CC.

Can u help me?

package {
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.utils.Timer;
    import flash.utils.getDefinitionByName;

    public class CatchingGame extends MovieClip {
        var catcher:Catcher;
        var nextObject:Timer;
        var objects:Array = new Array();
        var score:int = 0;
        const speed:Number = 7.0;

        public function CatchingGame() {
            catcher = new Catcher();
            catcher.y = 350;
            addChild(catcher);
            setNextObject();
            addEventListener(Event.ENTER_FRAME, moveObjects);
        }

        public function setNextObject() {
            nextObject = new Timer(1000+Math.random()*1000,1);
            nextObject.addEventListener(TimerEvent.TIMER_COMPLETE,newObject);
            nextObject.start();
        }

        public function newObject(e:Event) {
            var goodObjects:Array = ["Circle1","Circle1","Circle1"];
            var badObjects:Array = ["Square1","Square2", "Circle2"];
            if (Math.random() < .5) {
                var r:int = Math.floor(Math.random()*goodObjects.length);
                var classRef:Class = getDefinitionByName(goodObjects[r]) as Class;
                var newObject:MovieClip = new classRef(); 
                newObject.typestr = "good";
            } else {
                r = Math.floor(Math.random()*badObjects.length);
                classRef = getDefinitionByName(badObjects[r]) as Class;
                newObject = new classRef(); 
                newObject.typestr = "bad";
            }
            newObject.x = Math.random()*500;
            addChild(newObject);
            objects.push(newObject);
            setNextObject();
        }

        public function moveObjects(e:Event) {
            for(var i:int=objects.length-1;i>=0;i--) {
                objects[i].y += speed;
                if (objects[i].y > 400) {
                    removeChild(objects[i]);
                    objects.splice(i,1);
                }
                if (objects[i].hitTestObject(catcher)) {
                    if (objects[i].typestr == "good") {
                        score += 1;

                    } 
                    if (score < 0) score = 0;
                    scoreDisplay.text = "Score:" +score;
                    removeChild(objects[i]);
                    objects.splice(i,1);
                }

            }
            for(var k:int=objects.length-1;k>=0;k--){
            if (score == 3){finished.text="Well Done!";
                catcher.visible=false;
                scoreDisplay.visible=false;

                objects[k].visible=false;   }           


                }

            catcher.x = mouseX;

        }
    }
}

How can I import opening component at default package?

There is a button in opening component(welcome page) and it is invisible at the beginning. When user pass to another component, the button is supposed to be visible. However I cannot reach the property.

What is the way of importing opening component at (default package)?

this is the button:

<s:SWFLoader id="btnRepr" x="1790" y="1008.45" source="@Embed('Components/Starter/Assets/Buttons/ButtonReport.swf')" click="ShowReportPage" visible="false"/>

and this is the part I change visible to true:

btnRepr.visible = true;//Access of undefined property 'btnRepr'

mercredi 25 novembre 2015

Handling Editable Objects

Here's the scenario. A user selects an image, video, or other type of display object. It gets loaded inside a custom class known as EditableObject. The goal of EditableObject is re-sizing and re-positioning. EditableObject has 4 movieclips.

center_mc : Handles drag and drop and contains the display object.

rightside_mc : Handles re-sizing of width on mousedown

bottomside_mc : Handles re-sizing of height on mousedown

bottomright_mc : Handles scaling of object on mousedown

So far I can scale all parts of these objects. The bugs are what's causing trouble.

When I click down on the bottom or right side of the display object, the display object increases size from whichever side it's handling before I move the mouse. I get the amount to move based on the difference of the stageX and stageY positions of the mouse passed on MOUSE_DOWN and at the end of every MOUSE_MOVE. This isn't a problem, it just looks bad and currently solves the second bug..

When I handle bottomright_mc, I can only scale the object down. When trying to scale out, I have to position the mouse outside of EditableObject to get a difference greater than bottomright_mc's current position. This doesn't work because any attempts to exit the bounds of EditableObject trigger MOUSE_UP, even if I add the event listener using this.parent..

I want to be able to re-position and scale anything inside EditableObject using two sides and one corner of EditableObject when a mouse is held down and moved. Currently I can only move the object, scale the object less than its current size, and use the two sides to adjust the objects width and height but without having the mouse match the position of the side it's currently handling on initialization.

Here's an excerpt for the MOUSE_MOVE handler.

private function handleMouseMove(e:MouseEvent):void
            {
                    switch(dragType)
                    {
                            case "right":
                                    trace("Right triggered.");
                                    this.width = e.stageX - this.x;
                                    break;
                            case "bottom":
                                    trace("Bottom triggered");
                                    this.height = e.stageY - this.y;
                                    break;
                            case "bottomright":
                                    resizeMe(this, e.stageX - this.x, this.height);
                                    break;
                    }


                    prevMouseX = e.stageX;
                    prevMouseY = e.stageY;
            }

The full code for the class can be found here on pastebin.

Here's Editable Object in Adobe Flash CC EditableObject in Adobe Flash CC Here's EditableObject currently containing and handling an image inside the editor. enter image description here

AS3 concat // MovieClip(parent).variable.gotoAndStop(otherVariable);

Is there any concatenation problem in MovieClip(parent).robes_position_num_clicked.gotoAndStop(traje1); ?

When I click on item n°2, trace('robes_position_num_clicked') returns "robes_position2", which is correct & what expected, but

var index_clicked:int = myPositions.indexOf(e.target); // = Position num in array
var robes_position_num_clicked ="robes_position"+(index_clicked+1).toString();
  trace (robes_position_num_clicked);

 var traje1 = MovieClip(parent).robes_position1.currentLabel;

 if (   MovieClip(parent).robes_position1.currentLabel==traje1 &&  MovieClip(parent).robes_position1.currentLabel!=null)
    {   /*1*/ MovieClip(parent).robes_position2.gotoAndStop(traje1);
        /*2*/ MovieClip(parent).robes_position_num_clicked.gotoAndStop(traje1);   
      MovieClip(parent).robes_position1.gotoAndStop(1); 
    }

The first "sentance" /* 1*/ does the expected job,
while sentance /* 2*/ which is supposed to be a synonym, doesn't, and returns an error "One term is undefined and has no property"


Thanks for your lights as we say in french !

AS3 - set mcs to current label

I've got 3 dolls : sitting, jumping, and running. & I have dresses. All of my dresses models are designed in 3 positions : sitting, jumping & running.

  • dolls_btns contains 3 btns to choose the doll, who starts with undies, their name are : sitting_with_undies, jumping_with_undies, running_with_undies.
    (Undies are removed when a dress is applied).

  • dolls_mc contains :
    on frame 1 : nothing
    on frame 2 : sitting_with_undies, // label : sitting_with_undies
    on Frame 3 : sitting_naked, // label : sitting_naked
    on frame 4 : jumping_with_undies, // label : jumping_with_undies
    on frame 5 : jumping_naked, // label : jumping_naked
    on frame 6 : running_with_undies, // label : running_with_undies
    on frame 7: running_naked // label : running_naked

    • dresses_btns contains buttons which allow to choose the color of the dress

    • dresses_for_sitting contains:
      on frame 1: empty frame,
      on frame 2: 1 pink dress // label : pink_dress
      on frame 3: 1 red dress // label : red_dress
      on frame 4 : 1 green dress // label : green_dress
      and more dresses

    • dresses_for_jumping contains:
      on frame 1: empty frame,
      on frame 2: 1 pink dress // label : pink_dress
      on frame 3: 1 red dress // label : red_dress
      on frame 4 : 1 green dress // label : green_dress
      and more dresses

    • dresses_for_running contains:
      on frame 1: empty frame,
      on frame 2: 1 pink dress // label : pink_dress
      on frame 3: 1 red dress // label : red_dress
      on frame 4 : 1 green dress // label : green_dress
      and more dresses

Lets say I choose the sitting doll & then apply her a pink dress.
Next, if i click on dresses_btns.green_dress, as the doll is already set to sitting, the green sitting-shaped dress will come up. I can apply any other dress color, by clicking on my dresses_btns, as the position is set. // ok

But now if i click on running, the sitting-shaped dress doesn't disappear, as clicking on a doll only switches between dolls positions, but doesn't apply the correct shaped-dress.

So what i'm lookig for is :
1) I choose the sitting position & 2) apply it a pink dress. // ok, done
3) Then, when clicking on jumping > I want to remove the sitting pink dress, & replace it by jumping pink dress .


As I have many dresses, many positions, many hair styles, & clothes, & accessories, I need an easy way to manage all of my items, according to the last clicked position.

// here we are in dolls_btns

var myDolls = [sitting_with_undies, jumping_with_undies, running_with_undies];

for each ( var doll in myDolls)
{
    doll.addEventListener(MouseEvent.CLICK, onPositionClick);
    doll.buttonMode=true;
 }

function onPositionClick(e:MouseEvent):void
{ 
   MovieClip(parent).dolls_mc.gotoAndStop(e.target.name); // places the chosen doll's position on stage

if ( e.target == myDolls[2]  )  /// lets say I've clicked on running
     { 
         // what I'm trying to achieve : 
    if (  MovieClip(parent).dresses_for_sitting.currentLabel=="pink_dress")
       {  MovieClip(parent).dresses_for_sitting.gotoAndStop(1) // empty frame
          MovieClip(parent).dresses_for_running.gotoAndStop("pink_dress");    
          // That works, but I'd like to use dresses_for_sitting.currentLabel instead of naming each label one by one, as I have too many cases, clothes, hair colors, & hair styles, accessories, etc
       }
   } 
}

I've been searching the web for over 12 hours & tryied many solutions, in vain. I think currentLabel should do the trick but I lack of knowledge to complete my functions.

Anticipate thanks

Null reference, AS3

I'm creating a text based adventure game for my first flash game, at the moment I have got:

type writing effect

displaying parts in order

key down to continue/finish typing text

and so on.

Right now, I'm trying to make it so choices appear at the correct parts. I've done this but now I need to display clickable textbuttons that run the choice (I'm using flashdevelop). I got some code from this thread (second answer)

trying to create the list of choices:

    for (var i:int = 0; i < optionsArray[currentChoicePart].length; i++) 
    {
        var textButton:Sprite = getTextButton(optionsArray[currentChoicePart][i])
        textButton.x = myTextField.x
        textButton.y = stage.stageHeight / 2 +50 - (i * 25)
        choicesOnScreen[textButton.name] = textButton // erroring line
        addChild(textButton)
    }

when this runs, the line with the comment "erroring line" saying that textButton is a null value. (choicesOnScreen is a dictionary)

Multiple Randomly Moving Instances in Flash

I've been trying to find a tutorial on creating multiple instances of the same MC, moving and bumping into each other in a defined area. There are many tutorials on how to do this with a script-generated 'ball', but I would like to do it with instances of a drawn MC that isn't a ball. I can't seem to find any direction on how to do that.

I suspect I should place them in an array and apply some physics to that array???

For those who know anything about biochemistry, I am trying to simulate the accumulation of acetyl-Choline in a synapse when a person is poisoned with an organophosphate. So imagine two synaptic terminals at the top and bottom of the screen, with a cluster of acetyl-choline molecules clogged up between them. I want the instances of 'acetyl_mc' to move around in that contained space without wandering off. In truth, they don't need to bounce off each other, just off the boundaries of the container. Advice?

XML node cannot traced

A web-service returns a XML over SOAP and I am trying to parse it. However I cannot reach nodes. I trace XML at all but nodes are untraceable.

<soap:Envelope xmlns:soap="http://ift.tt/18hkEkn" xmlns:xsi="http://ift.tt/ra1lAU" xmlns:xsd="http://ift.tt/tphNwY">
    <soap:Body>
        <SbDrsRprRspnse xmlns="http://tempuri.org/">
            <SbDrsRprRslt>
                <SODSRprDt>
                    <Aktiv>false</Aktiv>
                    <Silindi>false</Silindi>
                    <Sira>0</Sira>
                    <Numara>IL1</Numara>
                    <AdSoyad>Maksim Tsygalha</AdSoyad>
                    <ToplamEtk>30</ToplamEtk>
                    <TamamEtk>6</TamamEtk>
                    <Durum>20</Durum>
                    <Units>
                        <SbOgrtDSUnitRDt>
                            <Aktif>false</Aktif>
                            <Silindi>false</Silindi>
                            <UnitsAdi>Ünite 3</UnitsAdi>
                            <EtkTop>30</EtkTop>
                            <TamamEtk>6</TamamEtk>
                            <Durum>20</Durum>
                        </SbOgrtDSUnitRDt>
                    </Units>
                </SODSRprDt>
            </SbDrsRprRslt>
        </SbDrsRprRspnse >
    </soap:Body>
</soap:Envelope>

I can trace(returnXML) and see all things above. But when I try trace(returnXML.children().children().children()) it shows nothing. Also ==null, ==undefined, ==" ", and =="" returns false. What am I doing wrong?


edit

here is what I did after the comment;

private function ProcessXML(ref:XML):void
{
    var returnXML:XML = new XML(ref);
    var soap:Namespace = new Namespace("http://ift.tt/18hkEkn");
    trace(returnXML.soap::Body.SbDrsRprRspnse.SbDrsRprRslt.SODSRprDt.Aktif); //it returns nothing!
}


edit #2 I am using Flash Builder and it keeps throwing error for second namespace childrenNs - TypeError: Error 1080 - Illegal value for namespace. I have searched a little bit about the error but couldn't find something worthwhile. So maybe using a one namespace-soap just for testing that there is nothing else problematic. So is it possible to use only one namespace with this XML?

RegEx to normalize XML syntax

I have an XML-code where some tags generate xml parse errors (Error #1090). The problem is in attributes that need to be quoted:

<div class=treeview>

Help me please to write a regular expression to make them as following:

<div class="treeview">

mardi 24 novembre 2015

Drag and Drop Lines For Squares

I want to create a drag and drop program that i can create number of vertical or horizontal lines to form squares. But i don't know how to do it as i am a newbee. Cry for help. Thx so much!!!!!

Here is my fla file. Here is my code , I created two buttons that have the instance name called addLine and addLine2 , one for create vertical lines , and one for horizontal lines. THX MUCH!!!!!

var bWidth:Number = 1000; var bHeight:Number = 680; var grid:Number = 100; // Size of the grid and number of lattice points in each direction var dotsWide:Number = Math.ceil(bWidth/grid) - 1; var dotsHigh:Number = Math.ceil(bHeight/grid) - 1; stage.addChild(board); board.addChild(myLine); board.graphics.lineStyle(1,0); board.graphics.beginFill(0xCCCCCC); board.graphics.drawRect(0,0,bWidth,bHeight); board.graphics.endFill(); // Add a bunch of circles to represent lattice points board.graphics.beginFill(0x000000); for (var i=1; i<=dotsHigh; i++) { for (var j=1; j<=dotsWide; j++) { board.graphics.drawCircle(j*grid,i*grid,0.5); } } board.graphics.endFill(); board.x = 20; board.y = 20; addLine.addEventListener(MouseEvent.CLICK , addLineFunction); function addLineFunction(event:MouseEvent):void{ myLine.graphics.lineStyle(10,0); myLine.graphics.beginFill(0xFF5555); myLine.graphics.lineTo(0,100); myLine.graphics.endFill(); } addLine2.addEventListener(MouseEvent.CLICK , addLineFunction2); function addLineFunction2(event:MouseEvent):void{ myLine.graphics.lineStyle(10,0); myLine.graphics.beginFill(0xFF5555); myLine.graphics.lineTo(100,0); myLine.graphics.endFill(); } // Part II -- Add drag and drop functionality myLine.addEventListener(MouseEvent.MOUSE_DOWN, startMove); function startMove(evt:MouseEvent):void { stage.addEventListener(MouseEvent.MOUSE_MOVE, pointMove); } function pointMove(e:MouseEvent):void { myLine.x = goodX(board.mouseX); myLine.y = goodY(board.mouseY); e.updateAfterEvent(); } stage.addEventListener(MouseEvent.MOUSE_UP, stopAll); function stopAll(e:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE, pointMove); } // Part III -- Helper functions to stay within boundary AND snap to grid function goodX(inX:Number):Number { if (inX > grid*dotsWide) { return grid*dotsWide; } if (inX < grid) { return grid; } return grid*Math.round(inX/grid); } function goodY(inY:Number):Number { if (inY > grid*dotsHigh) { return grid*dotsHigh; } if (inY < grid) { return grid; } return grid*Math.round(inY/grid); }

AS3 dynamic data loading incorrectly

I am using PHP MySQL and AS3 to load dynamic data depending on the site number. The problem when i click next site, it adds an increment to the existing site and displays the new site, but for some reason doesn't remove the content from the old site?

MY PHP

$dbHost = "localhost";
$dbUser = "username";
$dbPass = "password";
$dbName = "dbname";
$dbTable = "tablename";

if (isset($_GET['sn'])) {
$sn = $_GET['sn'];
}

// connecting and selecting database
@mysql_connect($dbHost, $dbUser, $dbPass) or die(mysql_error());
@mysql_select_db($dbName) or die(mysql_error());

// getting data
  $data = "";
  $datatitle = "";
  $res = mysql_query("SELECT * FROM ".$dbTable." WHERE Site_ID='$sn'") or die(mysql_error());
  while($row = mysql_fetch_object($res)) {
    $data .= strip_tags($row->Site_Description);
}
die($data);

my AS3 package code:

package {

import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Loader;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.text.TextField;
import flash.events.IOErrorEvent;

public class App extends MovieClip {
    public static const URL:String = 'weburl/get.php';
    private var loader:URLLoader;
    private var request:URLRequest;
    public function App():void {
        output(" ");
        loadData();
    }

    var siteNumber = 2;     

    public function loadData():void {

        var randomParam:String = "?p=" + Math.floor(Math.random() * (10000000)) + "&sn=";
        this.loader = new URLLoader();
        request = new URLRequest(URL + randomParam + siteNumber);
        request.method = URLRequestMethod.POST;
        loader.addEventListener(Event.COMPLETE, onLoadData);
        loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFiledToLoad);
        loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFiledToLoad);
        loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFiledToLoad);
        loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFiledToLoad);
        loader.load(request);

        } 

    public function onLoadData(e:Event):void {
        output( e.target.data);
    }
    private function onDataFiledToLoad(e:IOErrorEvent):void {
        output("onDataFiledToLoad error=" + e.text);
    }

    public function output(str:String):void {
        var text:String = field.htmlText;
        field.htmlText = str + text;

    }

    function removeExisting():void {

            this.loader.close();
    }

  }


}

The code I am using on the frame

next_site1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandlernext_site1); 
            function mouseDownHandlernext_site1(event:MouseEvent):void 
            { siteNumber = siteNumber + 1;

                SiteNumberText1.text = siteNumber.toString();
                loadData();
            }
prev_site1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandlerprev_site1); 
            function mouseDownHandlerprev_site1(event:MouseEvent):void 
            { siteNumber = siteNumber - 1;

                SiteNumberText1.text = siteNumber.toString();
                loadData();

            }

I understand that you have to unload the data, but can't seem to find an effective solution.

I have looked at these questions below, but they were not useful:

xml data to dynamic text AS3 flash

AS3 Save & Load multiple text boxs data to local file(s)

Adobe Air SOL Location for OSX

So I currently have an air app I am working on that I plan on distributing out. One of the features I have is the ability to import other SWF's and record what happens on screen. Now on windows, users are able to take the cookies of the swf that's being imported and place them in a folder so my air app can load them. This folder for windows is:

C:\Users[username]\AppData\Roaming

And inside the roaming folder will be a folder with the app name, and inside is where you would place the cookie files.

However, some of my users are reporting on the OSX end that they can not find this folder anywhere. I just got off a two hour skype call with a friend of mine who uses OSX and we could not find this folder equivalent at all. We went through three pages worth of google results and can not find this. Any help is welcome, thank you very much.

Have any idea's of getting a new audio file to play with every click of this lesson?

I am somewhat new to AS but still trying to learn and accomplish what seems like tough stuff. I will prevail!

The code below shows my progress so far. I have a UI Loader that has a series of thumbnails. With each click of the thumbnail a new SWF file loads... well I'm trying to get an external series of mp3 files to do the same through an XML file. So far, I've managed to just get one audio file to play with every click AND it play over the existing file.

I simply want to get a new one to play with each thumbnail AND stop the previous audio file from playing if/when the user clicks a new thumbnail.

Please assist if possible...help me see the errors of my way. A little overwhelmed.

var imagesXML:XML;
var xmlLoader: URLLoader = new URLLoader();
xmlLoader.addEventlistener(Event.COMPLETE, xmlLoaded);
xmlLoader.load(new URLRequest("lessons/images/Images5.xml"));


/////////////////////////////////////////////////////////////
////////////    thumbnail loader    /////////////////////////

var mySound:Sound;
var myChannel:SoundChannel;


function xmlLoaded(evt:Event):void
{
imagesXML = new XML(xmlloader.data);
var thumbLoader:UILoader;
for(var i:uint = 0; i < imagesXML.image.length(); i++)
    {
        thumbLoader UILoader(getChildByName("thumb" + 1));
        thumbLoader.load(new URLRequest("lessons/images/thumbs/" + imagesXML.image[i].@file));
        thumbLoader.buttonmode = true;
        thumbLoader.addEventListener(MouseEvent.CLICK, thumbClicked);
        var fullPath:String = "lessons/images/file-1.swf";
        mainLoader.load(new URLRequest(fullpath));
    }
}



/////////////////////////////////////////////////////////////
////////////////   load Images  /////////////////////////////

function thumbClicked(evt:MouseEvent):void
{
    var thumbName:String = evt.currentTarget.name;
    var thumbIndex:uint = uint(thumbName.substr(5));
    var fullPath:String = "lessons/images/" + imagesXML.image[thumbIndex].@file;
    mainLoader.load(new URLRequest(fullPath));

//stop any sound playing
    if (myChannel != null)
    {
        myChannel.stop();
    }

// load mp3 file
    mySound = new Sound(); myChannel = new SoundChannel();
    mySound.load(new URLRequest ("lessons/audio/narration/ch1p3.mp3"));
    mySound.play();
}

e+ is added with string after converting from integer

After converting integer into string , at compile time string add up with e+ like in trace i am getting value 90 and in swf it is showing 9.0e+

public function getPlayerAttack(ourTeam:Boolean=true):String{
        var attackArr:Array=[];
        var num:int;
        var total:int=0;
        var _teamXML:XML;
        if (ourTeam)
            _teamXML=getOurTeamXml();
        else
            _teamXML=getOppTeamXml();

        for each (var playerList:XML in _teamXML.player.(@gp!="0")){

            if (playerList.@name!="TEAM"){
                var attackStat:String=getStat("attack_kills",playerList);
                num = int(attackStat);
                if(num >= 10)
                {
                total += num;
                attackArr.push(num);
                }
        }   
    }
var attackPer:int = getPercent(total,attackArr.length);
        var mytext:String = String(attackPer);
        trace(typeof mytext);
        return  mytext;
    }

Weird error AS3. Term undefined

so I'm getting an error at line 342 which is

myTextField.text = object[curPart]["text"]

it says that a term is undefined. Tracing curPart gives me a null value, although in code that runs literally moments for that one, curPart is part3. Nothing changes it. This is what runs before it, a type writing effect function.

private function addCharackter():void
{
    if (!textFinished)
    {
        // add the charackter to the Textfield
        myTextField.text = object[curPart]["text"].substring(0,counter)
        counter++
        trace(curPart) // prints "part3"
        // if you reached the end of the String stop Timer
        if (counter == object[curPart]["text"].length+1 && !textFinished)
        {
            textFinished = true;
            trace("Text finished:",textFinished)
            clearInterval(sInt)
            counter = 0;
            if (object[curPart]["text"].indexOf("What do you do?") >= 0)
            {
                trace("H!!!")
                choosing = true
                createOptions();
            }
            if (object[curPart]["text"].indexOf("What do you do?") >= 0)
            {
                dead = true;
            }
        }
    }

Another weird thing is that the error doesn't happen if I finish the type writing effect by pressing space which is done here:

public function onEnter(key:KeyboardEvent):void
{
    if (key.charCode == 32)
    {
        if (dead && textFinished && !choosing)
        {
            curPart = object[curPart]["lastPart"]
            textFinished = false
            dead = false;
            myTextField.text = ""
            counter = 0;
            sInt = setInterval(addCharackter, textSpeed)
        }
        if (!textFinished && !choosing && !dead)
        {
            trace(textFinished)
            trace("finishing")
            trace(curPart)
            myTextField.text = object[curPart]["text"]
            if (object[curPart]["text"].indexOf("What do you do?") >= 0)
            {
                trace("H!")
                choosing = true
                createOptions();
            }
            if (object[curPart]["text"].indexOf("You have died") >= 0)
            {
                dead = true;
            }
            clearInterval(sInt)
            textFinished = true;
        }
        else if (textFinished && !choosing && !dead)
        {
            trace("Hi!!!!")
            curPart = object[curPart]["nextPart"]
            myTextField.text = ""
            counter = 0;
            sInt = setInterval(addCharackter, textSpeed)
            textFinished = false
        }
    }
}

I've looked through my code for hours. text is inside part3 and part3 DOES exist, considering it works if I skip the typing process by pressing space. (it also doesn't happen if I were to skip the typing process before part3.)

edit: Another thing that I just realised, line 342 should never be ran because textFinished should equal true (which it is moments before, but when I press space, it magically isn't. I don't change it to false anywhere except in parts that aren't running when the error happens)

how to put timer in if condition

first thing this is not my code i just edit to make new things this is the code i edited, i want my rocket to drop down and stay for maybe 1 sec until it lunch. i did an animation on rocket to drop for 24frame.

this code makes my rocket drop because of animation but it was moving when it drop.

public class RocketMss extends MovieClip {

    var rocketSpeed:Number;
    var rocketTimer:Timer;
    var timing:Number;

     function RocketMss() {

        timing = 0;
        rocketSpeed = 12;
        addEventListener("enterFrame", enterFrame);
    }

    function enterFrame(e:Event){

        rocketTimer = new Timer(100);
        timing = 1;
        if(timing == 1){
            this.x += rocketSpeed;
            timing = 0;
            if((this.currentFrame == this.totalFrames) && this.x > 640){
                removeEventListener("enterFrame", enterFrame);
                stage.removeChild(this);
            }
        }


    }

thank you of your answer.

Why are my timer and score count not working?

I am trying to create a game using action script 3 and can't understand why the following code is resulting in my score immediately resetting to 0 and my timer rapidly changing numbers with no consistent pattern? Any help is much appreciated! Thank You!

import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;

var score:int=0;
var nCount:Number = 5;
var myTimer:Timer = new Timer(3000, nCount);
timer_txt.text = nCount.toString();

myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.start();

function countdown(e:TimerEvent):void{
        nCount--;
        timer_txt.text = nCount.toString();
}
init();
function init(): void {
        Mouse.hide();
        addEventListener(Event.ENTER_FRAME, update);
        addEventListener(MouseEvent.CLICK, checkIfHit);
}

function update(myEvent:Event):void{
        aim_mc.x = this.mouseX;
        aim_mc.y = this.mouseY;
        score_txt.text = "Score: " + score;
}

function checkIfHit(e:MouseEvent):void{
        for(var i:int = 1; i < 4;++i){
                var myClip:MovieClip = MovieClip(getChildByName("duck" + i));
                if (myClip.hitTestPoint(mouseX,mouseY,true)){
                        score = score + 1;
                        
                }
        }
}

lundi 23 novembre 2015

How to create webservice for online game

I created a game in flash, for android(I know flash is dead, but was the only platform I knew how to code a game). It's based on matches, I did the AI and the game works very well offline.

But now I want to make it online and I never developed anything for web, like websites, webservers. I do not even know what SOAP, REST and this methodologies are.

So what do I need to learn to develop something like this? Here are the requirements :

  • I want to create a "room" with your facebook friends that are online in the moment.
  • In this "room" you can invite them to play a match.
  • The information that is passed client to client is only two points in the cartesian plane(e.g., {(1,2), (3,5)}) and the information that the game may have ended.

It's important to notice that the server must hold connections from cellphones. The information passed is from cellphone to cellphone.

Develop the whole game in another language or platform is not an option. This is my first game that will be published, so its more like an learning exercise. I dont know PHP nor Python, but I can learn it.

Thanks.

ActionScript load extern gif animation into htmlText

all~

I'm trying to load a extern gif file into a textfield's htmlText. I set the htmlText to <img src='98.gif' />. Unfortunately the gif animation is not shown and it says ProcessImageTags: can't find a resource for export name '98.gif'.

The file '98.gif' is located in the same directory with my swf file.

How to solve this problem?

As3 Google Play Game Services ANE Error "The extension context does not have a method with the name..."

I have been using the As3 Google Play Game Services ANE and I am getting the error

ArgumentError: Error #3500: The extension context does not have a method with the name promptUserToSignInOnStartup.
at flash.external::ExtensionContext/_call()
at flash.external::ExtensionContext/call()
at com.google.api.games::Games$/promptUserToSignInOnStartup()
at Main()[C:\Apps\Hitt\Main.as:24]
at runtime::ContentPlayer/loadInitialContent()
at runtime::ContentPlayer/playRawContent()
at runtime::ContentPlayer/playContent()
at runtime::AppRunner/run()
at ADLAppEntry/run()
at global/runtime::ADLEntry()
Cannot display source code at this location.

I cannot figure out the problem, would someone be able to help me, I am using the ANE by alex69 from Github. Let me know if you need any more information. Thanks in advance!

Tween blur a movieclip using as3

I'm trying to tween a movieclip called "SmartBg" to blur from zero to 8% on trigger of a mouse click event on another movieclip. How do I go about achieving that?

Does the same String value always amount to the same String reference in AS3?

In AS3, do two Strings with the same value always have the same exact reference, without exception? In particular, I'm wondering if things like concatenated strings and strings returned from a web service can create duplicate instances of the same exact value.

For instance:

class Example
{
    const MY_STRING:String = "Example";
    .
    .
    .
    private function myWebMethodResultHandler(pResult:ResultEvent):void
    {
        var myWebMethodString:String = pResult.result as String;
        trace(myWebMethodString === MY_STRING); // returns true;
    }
    .
    .
    .
    private function someOtherFunction():void
    {
        var str1:String = "Ex";
        var str2:String = "ample";
        var concatenatedString:String = str1 + str2;
        trace(concatenatedString === MY_STRING); // returns true;
    }
}

Is it absolutely guaranteed that in every case, including the ones above, that two Strings in AS3 with the same value are also the same exact instance with the same exact reference, or are there any cases at all in which Strings could be stored separately and as duplicate instances, taking up twice as much memory (and causing String comparisons to be more complicated internally than just comparing two 32-bit references)?

error with hitTestObject AS3

in this TimerEvent I am trying to have the stars bounce off an object in the middle of the screen and I get this error TypeError: Error #1006: value is not a function. at ULTIKARLKATCHERV2_fla::MainTimeline/tickTock() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() Help!

function tickTock(e:TimerEvent) {

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

stars[i].x += xInc[i] ;
stars[i].y += yInc[i] ;
stars[i].rotation += 15 ;
if (stars[i].x >= 500 || stars[i].x <= 0) {
    xInc[i] *= -1
}else if (stars[i].y >= 375 || stars[i].y <= 0) {
    yInc[i] *= -1
}
if (stars[i].x.hitTestObject(balance)){
        xInc *= -1
    }
}

} (This is for my ICS4 Class and I need a 100% pls help

Instagram logout programatically

Adobe AIR, apache flex sdk, applicaiotn for instagram using Instagram API. When i need to logout user i use this simply code:

protected function logOut():void
        {               
            var urlRequest: URLRequest = new URLRequest();
            var urlLoader: URLLoader = new URLLoader();
            urlRequest.url = "http://ift.tt/1zyZ8Db";
            urlLoader.addEventListener(Event.COMPLETE, logOutCompleted)
            urlLoader.load(urlRequest);
        }

but it doesnt logouting, it stays logged with previous user. Any suggestions why request doesnt work?

Adobe Air integrate Flex Components

Im currently developing an Adobe Air application, using Adobe Flash CC 2005, Flash Builder 4.7, and Action-Scritp 3.

I notice that the UI Components like the List Component, dont scroll up or down with finger on mobile devices.

If im understanding right, the Flex Framework have Components like an List that support mobile.

Its posssible to integrate Flex Components to the currently Adobe Air project? If so, how?

reading tile-data from mbtiles generates "RangeError: Error #2006: The supplied index is out of bounds."

I am trying to read imagedata from a sqlite database ( it is a mbtiles map tiles file ) for that i tried to convert this php code

$sql = "SELECT * FROM tiles WHERE zoom_level = $zoom AND tile_column = $column AND tile_row = $row";
$q = $conn->prepare($sql);
$q->execute();

$q->bindColumn(1, $zoom_level);
$q->bindColumn(2, $tile_column);
$q->bindColumn(3, $tile_row);
$q->bindColumn(4, $tile_data, PDO::PARAM_LOB);

while($q->fetch())
{
header("Content-Type: image/png");
echo $tile_data;
}

to as3 using

        _conn = new SQLConnection();
        _conn.addEventListener(SQLEvent.OPEN, openHandler); 
        _conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
        var folder:File = File.applicationDirectory; 
        var dbFile:File = folder.resolvePath("test.mbtiles");
        _conn.openAsync(dbFile, SQLMode.READ);
        function openHandler(event:SQLEvent):void 
    { 
        trace("db opened"); 
        var selectStmt:SQLStatement = new SQLStatement(); 
        selectStmt.sqlConnection = _conn; 
        selectStmt.text = "SELECT * FROM tiles WHERE zoom_level = 5 AND tile_column = 17 AND tile_row = 20"; 
       selectStmt.execute();
    } 

but i am getting "RangeError: Error #2006: The supplied index is out of bounds."

Any ideas on how to solve this? Thanks!

I have two externally loaded SWF files and I would like for each to recognize that the other has loaded or !loaded?

After loading 2 SWF files via two separate buttons, I am attempting to get one to recognize that the other is being viewed and unload. What would be the best way given the code here?

function matrixLoad(event:MouseEvent): void
{
if (fl_ToLoad3)
{
    fl_Proloader3 = new fl_Proloader3();
    fl_Proloader3.load(new URLRequest("assets/matrix1.swf"));
    addChild(fl_Proloader3);
    fl_Proloader3.x = 0;
    fl_Proloader3.y = 300;
    trace("Matrix1 Load");
}
else
{
    fl_Proloader3.unload();
    removeChild(fl_Proloader3);
    fl_Proloader3 = null;
    trace("Matrix1 UnLoad");
}
fl_ToLoad3 = !fl_ToLoad3;
}

function matrixLoad2(event:MouseEvent): void
{
if (fl_ToLoad4)
{
    fl_Proloader4 = new fl_Proloader4();
    fl_Proloader4.load(new URLRequest("assets/matrix2.swf"));
    addChild(fl_Proloader4);
    fl_Proloader4.x = 0;
    fl_Proloader4.y = 300;
    trace("Matrix2 Load");
}
else
{
    fl_Proloader4.unload();
    removeChild(fl_Proloader4);
    fl_Proloader4 = null;
    trace("Matrix2 UnLoad");
}
fl_ToLoad4 = !fl_ToLoad4;
}


matrix1.addEventListener(MouseEvent.CLICK, matrixLoad);
matrix2.addEventListener(MouseEvent.CLICK, matrixLoad2);

As3 flash error “Cannot access a property or method of a null object reference”

I came up with this error when testing my movie

TypeError: Error #1009: Cannot access a property or method of a null object reference. at ACTUALPROJECT_fla::MainTimeline/youLose()[ACTUALPROJECT_fla.MainTimeline::frame3:112] at ACTUALPROJECT_fla::MainTimeline/SharkEat()[ACTUALPROJECT_fla.MainTimeline::frame3:87]

this is my code

import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.*;
import flash.utils.Timer;

var rectangle:Rectangle = new Rectangle(0,345,600,455);

turtle_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
turtle_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
turtle_mc.addEventListener(Event.ENTER_FRAME, handleCollision);
turtle_mc.addEventListener(Event.ENTER_FRAME, handleCollision2);
turtle_mc.addEventListener(Event.ENTER_FRAME, handleCollision4);
turtle_mc.addEventListener(Event.ENTER_FRAME, SharkEat);
turtle_mc.buttonMode = true;
turtle_mc.originalY = turtle_mc.y;
turtle_mc.originalX = turtle_mc.x;

function resetTurtlePosition()
{
    turtle_mc.y = turtle_mc.originalY;
    turtle_mc.x = turtle_mc.originalX;
}

function pickupObject(event:MouseEvent):void
{
    event.target.startDrag(false, rectangle);
}

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


function handleCollision(e:Event):void
{


    if (plasticBag_mc.hitTestPoint(turtle_mc.x,turtle_mc.y,false))
    {

        youLose();

    }
    else
    {

    }
}
function handleCollision2(e:Event):void
{


    if (fishingBoat_mc.hitTestPoint(turtle_mc.x,turtle_mc.y,false))
    {

        youLose();

    }
    else
    {

    }
}
function handleCollision4(e:Event):void
{


    if (oilSpillBoat_mc.hitTestPoint(turtle_mc.x,turtle_mc.y,false))
    {

        youLose();

    }
    else
    {

    }
}
function SharkEat(e:Event):void
{


    if (shark_mc.hitTestPoint(turtle_mc.x,turtle_mc.y,false))
    {

        **youLose();**

    }
    else
    {

    }
}
var nCount:Number = 0;
var myScore:Timer = new Timer(10,nCount);
counter_txt.text = nCount.toString();
myScore.start();
myScore.addEventListener(TimerEvent.TIMER, countdown);
function countdown(e:TimerEvent):void
{
    nCount++;
    counter_txt.text = nCount.toString();

}

function youLose():void
{
    myScore.stop();
    turtle_mc.stopDrag();
    resetTurtlePosition();
    **this.storedtxt = counter_txt.text;**
    gotoAndStop(3,"PlayTheGame");
}

i have marked the two lines with asterix. I'm new to flash and AS3, can anyone help me out?

ActionScript3 - Drawing video(webcam) output on BitmapData with shifted position

I'm trying to draw a video(webcam) output on a Bitmapdata, it works if the position of the video is at (0,0) but when I shift the video to (200,0), the drawn output also shifted.

The code is pretty simple

// omitted for brevity

var videoContainer:Sprite = new Sprite();

// Video is added
videoContainer.addChild(video)

// position is offsetted
videoContainer.x = 200;
videoContainer.y = 200;
this.addChild(videoContainer)

// Generate Bitmap
var bd:BitmapData = new BitmapData(video.width, video.height, false, 0x0);
bd.x = video.x;
bd.y = video.y + video.height;
this.addChild(bd);

this.addEventListener(Event.ENTER_FRAME, onEnterFrame);

function onEnterFrame(e:Event):void {
    // start drawing
    bd.lock()
    bd.draw(video);
    bd.unlock();
}

enter image description here

I've tried to reposition it with a matrix, but apparently the entire original source had changed.

Is there a way to ensure that the output remains at (0,0) even if the videoContainer were offsetted from (0,0)?

How do I iterate through this object properly AS3

So I've made a object array(?) like this: http://ift.tt/1XkI1z9

I need to iterate through the choices of part1

I am currently trying this: http://ift.tt/1NmN42x

but I only get 1 textfield and that says 2 (even though there should be 2 text fields that go 1, 2)

dimanche 22 novembre 2015

Optimum tile size/layout in a space

This is for an air app but I'm sure it's a common issue for other things.

I've really been struggling to work out the best way to size tiles in a grid. I've got something like the code below, which kind of works but the problem I'm having is that the whole thing scales down too much on small screens.

I'm trying to find an optimum way of scaling a number of tiles so they fit the screen and stay the largest size possible. I could implement scrolling but I'd like to avoid that.

Is there a less convaluted/more effective way of arranging and scaling tiles to fit in a space?

        var scaleFactor:Number = Model.appScale * this.scaleX;


        var gap:Number = 10 /scaleFactor;
        var _width:Number = stage.fullScreenWidth / scaleFactor;
        var sampleWidth:Number = sample.width;
        var sampleHeight:Number = sample.height;

        var _scale:Number = 1;
        var colWidth:Number = sampleWidth + gap;
        var totalWidth:Number;
        var columns:Number = 0;
        var rows:Number = 0;


            do{
                rows ++;
                columns = Math.ceil(_children.length/rows);
                totalWidth = columns * colWidth;

                if(rows > Math.sqrt(_children.length) && totalWidth > _width)
                    _scale = (_width/totalWidth) * _scale;

                totalWidth = columns * colWidth * _scale;
            }
                while(totalWidth > _width)




        var top:Number = - ((rows * (sampleHeight + gap)) + (gap *2)) * _scale;

        // if it's too big scale it down
        var pt:Point = localToGlobal(new Point(0, 0));

    if(Math.abs(top) > pt.y/scaleFactor){

            _scale = (((pt.y - (bg.height + gap))/scaleFactor)/Math.abs(top)) * _scale;
            top =  -pt.y/scaleFactor;
        }


        var col:int = 0;
        var row:int = 0;

        for each(var button:MenuRenderer in _children)
        {

            Tweener.addTween(button,{
                x : _0x +  (((sampleWidth + gap) * _scale) * col),
                y : top +  (((sampleHeight + gap) * _scale) * row),
                scaleX: _scale,
                scaleY: _scale,
                time: 0.05 * button.order,
                transition: "easeInOut"
            });

            col ++;

            if(col == columns)
            {
                row ++;
                col = 0;
            }

        }

How to parse number from middle of string

I need to parse some numbers from a string, I can get the last number easily but wonder how to get the number mid string reliably. In this case the number 12?

var mystring = 'group 999999999 group-session-info 12 of 50';
var i;
var num; //how to get num "12"
var numOf;
i= mystring.lastIndexOf(" ");
if (i != -1) {
   numOf= mystring.substr(i);
}
alert(numOf); // = 50

Thanks

C# / ActionScript with AxShockwaveFlash

I am new to ActionScript and am trying to communicate between AS and C#. Every tutorial/explanation I find seems to be exactly the same, but I simply cannot get it to work. callFunction throws a COM exception ("E_FAIL"), and when I try calling ExternalInterface.call() from the AS, it never seems to.

I've gotten this to work in JavaScript/HTML, but I'm out of ideas for C#; I suspect I'm doing something wrong/not allowed in my AS. I compile the AS file with Adobe Flex 4.6 and mxmlc. Here is my AS file:

package
{
    import flash.external.ExternalInterface;
    public class Test
    {     
        public function Test()
        {
            ExternalInterface.call("someFct", "Hello world");
        }
    }
}

And in C# I have an AxShockwaveFlash control in WinForms:

private void InitializeComponent()
{
    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
    this.axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash();
    ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).BeginInit();
    this.SuspendLayout();
    // 
    // axShockwaveFlash1
    // 
    this.axShockwaveFlash1.Enabled = true;
    this.axShockwaveFlash1.Location = new System.Drawing.Point(104, 67);
    this.axShockwaveFlash1.Name = "axShockwaveFlash1";
    this.axShockwaveFlash1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axShockwaveFlash1.OcxState")));
    this.axShockwaveFlash1.Size = new System.Drawing.Size(574, 314);
    this.axShockwaveFlash1.TabIndex = 0;
    this.axShockwaveFlash1.FlashCall += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FlashCallEventHandler(this.recv);
    this.Click += new System.EventHandler(this.Form1_Click);
//...
    ((System.ComponentModel.ISupportInitialize)(this.axShockwaveFlash1)).EndInit();
     this.ResumeLayout(false);
}

Initializing the SWF object and receiving its call:

private void Form1_Click(object sender, EventArgs e)
{
    axShockwaveFlash1.LoadMovie(0, @"mypath\test.swf");
}

//Never executes
public void recv(object sender, _IShockwaveFlashEvents_FlashCallEvent e)
{
    string s = e.request;
}

How to set only one object to spawn with a timer?

I am currently a beginner trying to learn programming with as3 so bare with me. I have this code so far and my game repeatedly spawns the Food2 (golden apple) but it does not stop. My game also does not pause on frame 1 to allow me to press the button in order to start the game. Here is my code so far:

package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; 
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;

public class Main extends MovieClip{
    const speed:int = 10;
    var score:int;
    var vx:int;
    var vy:int;
    var gFood:Food;
    var gFood2:Food2;
    var head:SnakePart;
    var SnakeDirection:String;
    var snake:Array;
    var upPressed:Boolean = false;
    var downPressed:Boolean = false;
    var leftPressed:Boolean = false;
    var rightPressed:Boolean = false;
    var myTimer:Timer = new Timer(10000,1);

    public function Main(){
        gotoAndStop(1);
        init();
    }
    function init():void {
        vx = 1; vy = 0;
        score = 0;
        snake = new Array();
        SnakeDirection = "";
        addFood();
        myTimer.start();
        head = new SnakePart();
        head.x = stage.stageWidth/2;
        head.y = stage.stageHeight/2;
        snake.push(head);
        addChild(head);
        stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
        start1.addEventListener(MouseEvent.CLICK, startgame);
        help1.addEventListener(MouseEvent.CLICK, helpplayer);
        stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
        addEventListener(Event.ENTER_FRAME , onEnterFrame);
    }
    private function startgame(event:MouseEvent):void {
        gotoAndPlay(3);
        stop();
    }
    private function helpplayer(event:MouseEvent):void {
        gotoAndPlay(2);
        stop();
    }
    function addFood():void {
        gFood = new Food();
        gFood.x = 50 + Math.random()*(stage.stageWidth-100);
        gFood.y = 50 + Math.random()*(stage.stageHeight-100);
        addChild(gFood);
    }
    function addFood2():void {
        gFood2 = new Food2();
        gFood2.x = 70 + Math.random()*(stage.stageWidth-100);
        gFood2.y = 70 + Math.random()*(stage.stageHeight-100);
        addChild(gFood2);
    }
    function reset():void {
        score = 0;
        removeChild(gFood);
        removeChild(gFood2);
        myTimer.stop();
        addFood();
        head.x = stage.stageWidth/2;
        head.y = stage.stageHeight/2;
        vx = 1;vy = 0;
        for(var i = snake.length-1;i>0;--i){
            removeChild(snake[i]);
            snake.splice(i,1);
        }
    }
    function onKeyDown(event:KeyboardEvent):void{
        if(event.keyCode == Keyboard.LEFT){
           SnakeDirection = "left";
        }else if (event.keyCode == Keyboard.RIGHT) {
           SnakeDirection = "right";
        }else if (event.keyCode == Keyboard.UP) {
            SnakeDirection = "up";
        }else if (event.keyCode == Keyboard.DOWN) {
            SnakeDirection = "down";
        }
    }
    function onKeyUp(event:KeyboardEvent):void {
        if(event.keyCode == Keyboard.LEFT) {
            SnakeDirection = "";
        }else if(event.keyCode == Keyboard.RIGHT) {
            SnakeDirection = "";
        }else if(event.keyCode == Keyboard.UP ) {
            SnakeDirection = "";
        }else if(event.keyCode == Keyboard.DOWN){
            SnakeDirection = "";
        }
    }
    function onEnterFrame(event:Event):void {
        Timerfood();
        txtScore.text = "Score:" + String(score);
        if(SnakeDirection == "left" && vx != 1) {
            vx = -1;
            vy = 0;
        }
        else if(SnakeDirection == "right" && vx != -1) {
            vx = 1;
            vy = 0;
        }
        else if(SnakeDirection == "up" && vy != 1) {
            vx = 0;
            vy = -1;
        }
        else if(SnakeDirection == "down" && vy != -1) {
            vx = 0;
            vy = 1;
        }
        if(head.x - head.width/2 <= 0){
            score = 0;
            reset();
        }
        if(head.x + head.width/2 >= stage.stageWidth){
            score = 0;
            reset();
        }
        if(head.y - head.height/2 <= 0){
            score = 0;
            reset();
        }
        if(head.y + head.height/2 >= stage.stageHeight){
            score = 0;
            reset();
        }

        for(var i = snake.length-1;i>0;--i){
            snake[i].x = snake[i-1].x;
            snake[i].y = snake[i-1].y;
        }
        head.x += vx*speed;
        head.y += vy*speed;

        for(var i = snake.length-1;i>=1;--i){
            if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
                reset();
                break;
            }
        }
        if(head.hitTestObject(gFood)){
            score += 1;
            removeChild(gFood);
            addFood();
            var bodyPart = new SnakePart();
            bodyPart.x = snake[snake.length - 1].x;
            bodyPart.y = snake[snake.length - 1].y;
            snake.push(bodyPart);
            addChild(bodyPart);
        }
        if(head.hitTestObject(gFood2)){
            score += 2;
            removeChild(gFood2);
            addFood2();
            var bodyPart = new SnakePart();
            bodyPart.x = snake[snake.length - 1].x;
            bodyPart.y = snake[snake.length - 1].y;
            snake.push(bodyPart);
            addChild(bodyPart);
        }
        function Keyboard_a(event:KeyboardEvent):void {
            if (event.keyCode == 82) {
            resetgame();
            }
        }
        function resetgame():void {
            score = 0;
            if (contains(head))
                removeChild(head);
            init();
        }
        }
        function Timerfood():void {
            var myTimer:Timer = new Timer(10000,1);
            myTimer.addEventListener(TimerEvent.TIMER, timerListener);
            function timerListener(e:TimerEvent):void{
                trace("Timer is Trigered");
                addFood2();
            }
            myTimer.start();
        }
    }
}