samedi 31 décembre 2016

How to remove all MovieClips, Sprites and graphics from a scene in AS3?

I have a scene including all MovieClips, Sprites, graphics that I bring some of them to the stage using addChild(...).

I want to remove all of them because I can still see them when I go to other scenes.

I have used below code but it shows me the error mentioned below:

btn.addEventListener(MouseEvent.CLICK,removing);

function removing(e:MouseEvent):void
{
  while (stage.numChildren > 0)
  {
    stage.removeChildAt(0);
  }

}

Error:

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

Thanks in advance for your time and help!

Math.random in nested "for" loop not being random on each iteration in AS3

I have a function that takes a color and returns a similar color using Math.random

function randomizeColor(c:uint, off:int):uint{
    return Math.random() * off + c;
}

I have a Sprite that I construct instances of 26*8 times using a nested set of for loops. I have two different but similar methods for assigning a color to these Sprites. The first, which doesn't work, is to have the randomizeColor function be a function in the Sprites class .as file. Looks like this:

public function MySprite (w,h,color):void {
    var c:uint = colorRandomizer(color,15);
    // draw shape using new color "c"
}

private function colorRandomizer(c:uint,off:int):uint {
    // same function as above 
}

This strangely gives me 8 random colors repeated 26 times! 8 unique colors every time I restart the app.

However, if I instead pass an already randomized color to the constructor, I get a random color each of the 26*8 times the constructor is called. I've even followed the playhead through in debug mode and it iterates through the inner loop 8 times, getting random colors, and then increments the outer loop one time and then proceeds to return the same 8 colors on the inner loop. What gives?

Oh and here is what my for loops like ok like when it doesn't work

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var s:mySprite = new MySprite(10,20,colorArray[i]);
    }
}     

So this should pass 8 preset colors 8*26 times (one preset color each time, 8 presets total) and then that color gets passed to the randomizing function in the class which then draws the shape filled with the returned randomized color. If instead I do

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var randColor:uint = randomizeColor(colorArray[i],15);

var s:mySprite = new MySprite(10,20,randColor); } }

and change the constructor to just accept and use the color passed to it. When I do that, I get unique colors in each and every mySprite, not just for the inner for loop which then gives me 8 repeating colors. I'm probably over explaining at this point. Let me know if it's not clear. My code is simple enough you should be able to implement it easily in your own quick project to see it working and not working.

So even though I have a solution already, I want to know what is wrong with my understanding of the Math.random function or nested for loops or whatever my misunderstanding is. Do you see where my error in thinking or coding is?

source\com\gchats\visichat\clips\publicmessage.as, Line 447 This statement is not permitted in a class definition

I don't know what's the problem. I am new to actionscript

if(mutebtn._currentframe == 1)
{
    mutebtn.gotoAndStop(2);
    com.gchats.visichat.factory.getClass("userlist").onMute(true);
} else {
    mutebtn.gotoAndStop(1);
    com.gchats.visichat.factory.getClass("userlist").onMute(false);
}

vendredi 30 décembre 2016

Ease of Motion, Programming Tweening, c++

Tweening is a video editing term used to describe ease of motion. For example, with an elevator the lift does not go full speed and dead stop when it reaches it's desired floor. It knows what floor its on, what floor it is going to, and how long it will take to get there. Then it uses that data to smooth its motion.

I would like to be able to program this smooth motion for my projects by using tweening.

The method for how to do this is layed out in http://ift.tt/2ineIQk

Specifically looking at pg207-211

This guide explains what tweening is and then shows code in Action Script. To be honest I feel kind of stupid becuase I've tried to use the examples provided but I can't seem to replicate it in another language such as c++, java, javascript, or lua.

I do not wish to use a package or plugin to code tweening, I want to learn how to actually code a tweening function. So if anyone with better comprehension skills, or programming skills, thinks they understand then I would very much appreciate an explanation.

Sample Action script functions...

Math.easeInQuad = function (t, b, c, d) {
return c*(t/=d)*t + b;
};

Math.easeOutQuad = function (t, b, c, d) {
return -c * (t/=d)*(t-2) + b;
};

Math.easeInOutQuad = function (t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
};

Please help how to take instance name wich numbering by array and the number can be operated?

please help me how to solve this i ve been made snake and riddle game in education for assessing student competency

this script for player moving by clicking the button, the array is the place they could be. so the number must be operated

thaks for your help

a.addEventListener(MouseEvent.CLICK,bergerak);
b.addEventListener(MouseEvent.CLICK,bergerak);
c.addEventListener(MouseEvent.CLICK,bergerak);
d.addEventListener(MouseEvent.CLICK,bergerak);


function bergerak (Event:MouseEvent){
        var namatombol:String=Event.currentTarget.name;
        var myarray:Array=[];
                for (var i:int=0;i<3;i++){
                        myarray[i]=this["kotak"+i]; // (i) can be operated like this i+12 then (i) also can merge with string (kotak) in instance name
                        if (namatombol=="a"){
                                MovieClip(root).pemain.x=MovieClip(root).myarray[i].x;
                                MovieClip(root).pemain.y=MovieClip(root).myarray[i].y;
}
}
}

jeudi 29 décembre 2016

Can we change a variable in .fla file and then pass it to a class (.as) in Action Script 3?

I have a question regarding to the public variables in AS3.

Can I define a variable in .as file and then make some changes on it in the .fla file and the pass it to the same or other .as files consist of the new values in Action Script 3?

Thanks in advance!

How to pass variables from .fla file to .as file in as3

I have a .fla fine names test.fla and I have this variable in it:

var my_var;

stage.addEventListener(MouseEvent.CLICK, onLoaded);

function onLoaded(e:Event):void
 {
  my_var = "myVariable";
  //trace(my_var);
}

I have a .as file called Main.as.

I want to pass my_var from test.fla to the Main.as.

I will really appreciate, if you can help me in this matter!

It is noticeable that I have used the method mentioned in "Actionscript 3 : pass a variable from the main fla to external as file", but it does not work for me!!!

I wrote in my Main.as:

package 
{
 public class Main extends Sprite 
 {
  public function Main() 
  {
   trace(root.my_var);
  }
 }
}

Thanks in advance!

load multiple external SWF's to unknown number of movieclips and control them (AS3)

I'm creating a multi-player game that every user can join it. I want to load some assets to every user who going to join, but to be able to control them when user is doing some actions. For example, if the user is going forward, the asset will gotoAndStop at frame number 2.

I know that I can load SWF and control them by creating a variable of movieclip (myLoader.data); but I can't create unknown num of variables.

I have tried to do something like this:

var asset:MovieClip;
var myLoader:Loader = new Loader;
myLoader.load(new URLRequest("Asset_1.swf"));
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE , onCom);
function onCom(e:Event):void{
    asset = MovieClip(e.target.content.HOV_1);
    myUser.assetsCont.addChild(asset);
}

but when I'm doing this:

myUser.assetsCont.asset.gotoAndStop(2);

It's giving me an error. What can I do?

mardi 27 décembre 2016

Send an email with text and a snapshot attachment from Flash

Long story short, I'm trying to send an email with some dynamic text and have an image attached. The text part wasnt much of a feat. The image, however, is another thing. I've managed to get this piece of code working:

var tShC:String;
var tBnC:String;
var tStC:String;
var tMsC:String;
var hCh:String;
var lCh:String;
var fCh:String;
var sCh:String;
var pOll:String;

send.addEventListener(MouseEvent.CLICK, emailSmeta);

function emailSmeta(e:MouseEvent):void {

/*var bitmapData:BitmapData = new BitmapData(800, 600);
bitmapData.draw(stage);

var jpgEncoder:JPGEncoder = new JPGEncoder(90);

var image:ByteArray = jpgEncoder.encode(bitmapData);*/

getAllPrices();
var formVariables:URLVariables = new URLVariables();
//formVariables.jpg = image;
formVariables.senderEmail = "My msg;
formVariables.senderMsg = "Price list for: " + choice + heightTotal + " м" + "\n" +
                            tShC + "\n" +
                            tBnC + "\n" +
                            tStC + "\n" +
                            tMsC + "\n" +
                            hCh + "\n" +
                            lCh + "\n" +
                            fCh + "\n" +
                            sCh + "\n" +
                            "Total: " + pOll + "\n";
var variableRequest:URLRequest=new URLRequest("http://myadress/elkamailer.php");
variableRequest.method = URLRequestMethod.POST;
variableRequest.data = formVariables;


var variableLoader:URLLoader = new URLLoader();
variableLoader.load(variableRequest);
variableLoader.dataFormat = URLLoaderDataFormat.TEXT;

    try{
    loader.load(request);
    }
    catch (error:Error) {
    trace("it somewhat works");
    }
}

The image never comes though (yes i know it's commented right now). I've got this feeling I'm missing a tiny bit of info to make things work, but I cant figure what exactly if wrong here. Addtionaly, I've tried a ready solution from here(the very last one). It looks really neat, and almost made it working, just got this error ReferenceError: Error #1065: Variable bitmapData is not defined. My current PHP file is as simple as possible - two $_POST methods to get senderEmail and senderMsg variables, and a mail() function. I did find some more complex solution, but they were bit too... complex? I can hardly even try using stuff I barely understand. Any ideas how get this stuff running? Thanks in advance!

lundi 26 décembre 2016

Which code should I learn for making apps (android, ios, windows phone)

I've learn, since 3 years, ActionScript 3 and I'm able to make full functional apps on Android and IOS with Adobe AIR. I love AS3 but it seems that the world doesn't love Adobe...

Everytime I tell someone that I'm coding in ActionScript3, they told me that I shouldn't..

So, I think I have to learn a new code for developing apps.

Which one should I use for developing on Android and IOS (and, why not Windows phone..?) ? And which software should I use ? (I'm using Adobe Animate CC right now, obviously).

Thx for your advices.

Animate CC advances to the next frame with gotoAndStop commented out?

I'm writing this code that tests your reaction time and then advances to the next frame. It shows a box and then time the difference between when the box appeared and when the use presses [A]. Heer is my code

import flash.utils.Timer;
import flash.events.Event;
import flash.utils.getTimer;

stop();
        var canPress = false;
        var startClock:Timer = new Timer(4000+Math.random()*6000, 1);
        grbox.y = -500;
        startClock.start();
        var startTime:int = 0;

function displayBox(evt:Event):void{
        canPress = true;
        grbox.y = 143;
        var startTime:int = getTimer();
}

function Tpressed(e:KeyboardEvent):void
{
   if(e.keyCode==Keyboard.A){
                if(canPress==true){
                var endTime:int = getTimer();
                score1 = endTime-startTime;

                if(score2<0){
                        //gotoAndStop(3);
                }
                else{
                        //gotoAndStop(4);
                }
   }
   }

}

stage.addEventListener(KeyboardEvent.KEY_DOWN, Tpressed);
startClock.addEventListener(TimerEvent.TIMER, displayBox);

For some reason if I just spam the [A] button it will advance to the next frame. Why is this happening?!?! My 'gotoAndStop(4);' command is commented out so it should do anything, yet it is.

Flash AS3 read proxy server response with URLLoader

I am running an embedded flash 'swf' inside a LAN network with a proxy server. Proxy server interrupts some urls and returns my usage information. I am trying to access this information by sending those urls. I can see this traffic in firebug ,But the URLLoader does not seem to read it. Neither Complete event or progress event get fired. I tried URLStream with a timer also,but availableBytes were always zero.Is it possible to read this information?

  private var getLoader:URLLoader() = new URLLoader();
  private var sendRequest:URLRequest = new URLRequest();
  public function XDomain() {
   sendRequest= new URLRequest("requesturl");
   getLoader.addEventListener(Event.COMPLETE, eventHandler);
   getLoader.addEventListener(ProgressEvent.PROGRESS,eventHandler2);
   getLoader.load(sendRequest);
  }
  private function eventHandler(event:Event):void {
    trace("running");
  }
  private function eventHandler2(event:ProgressEvent):void {
   trace("runninhg progresss");
  }

Thanks in advance (It is not a crossdomain issue. I can see the response in firebug)

Should I mention in my resume that I have experience porting code? [on hold]

Ported program from ActionScript3 to JavaScript, and JavaScript to PHP. (Tho I developed and designed the project myself, so maybe it's a bad idea to mention the second part, as it would seem like I didn't design it well, and had to change the technology mid-way?)

Also, should I specifically mention that I developed websocket servers in PHP? Or is it just redundant?

dimanche 25 décembre 2016

Openfl error after installing

I installed open-f,ll lime, format . and when i try to run open-fl command this error appear :

open-fl' is not recognized as an internal or external command, operable program or batch file

How to properly override getters and setters in Haxe

I'm kind of new to Haxe but I have a lot of experience in ActionScript 3. Right now I'm porting one of my frameworks from AS3 to openfl, but I'm kind of stuck with getters and setters. Some of the framework components extends from openfl.display.DisplayObject (Sprite, to be exact) which already defines fields for width and height. But in my ComponentBase class I need to override these properties. In AS3 I'm doing it like this:

private var _width:Number = 0;

override public function get width():Number {
    return _width;
}
override public function set width(value:Number):void {
    _width = value;
}

But it doesn't work in Haxe. If I do it like this

override function get_width():Float {
    return _width;
}

It won't compile because it wants a physical field. But I also cannot redefine width and height values because they are already defined in base class.

You may ask why am I not using the values 'width' and 'height' defined in the base class. That's because sometimes I need to access those variables not thru the getter/setter accessors but directly. For example, I have a call to layout() method inside width and height setters, but I want to calculate it many times and call layout() only once.

Right now I decided to use Java-style getters and setters to make the job done, but it's not the best way. E.g.

public function setWidth(value:Float):Void {
    _width = value;
}

So, the question is: is it possible to make Haxe getters and setters use some value which has the name different than they're supposed to access?

samedi 24 décembre 2016

Is there a way to get requests to work when calling from a localhost for testing

I'm getting the errors when testing my application locally since I switched to https:

Warning: Domain www.example.com does not specify a meta-policy.

Applying default meta-policy 'master-only'. This configuration is deprecated. See http://ift.tt/TZoLx3 to fix this problem.

Error: Request for resource at http://ift.tt/2iquixC by requestor from http://localhost:8888/Test-debug/Test.swf is denied due to lack of policy file permissions.

I tried changing my localhost to https but got the following error:

Secure Connection Failed

An error occurred during a connection to localhost:8888. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG

The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the website owners to inform them of this problem.

From what I've read I can upload and add a policy file and changing secure to true but I don't want to allow calls from anywhere. Once the swf is on my server everything works fine.

Is there a way to get this to work locally for testing? Is there something that I can enable while testing like:

Security.allowDomain("localhost");

Or do I have to upload a cross domain policy and then delete that policy when I'm done testing?

EnterFrame listener that rotates sprite KILLS my framerate?

Well, I'm not quite a newbie, and not nearly an expert, but I find this very strange. I have a class that creates an array of images and rotates through them in an ENTER_FRAME listener function, a la animated gif.
Fine.
I added another ENTER_FRAME listener that rotates the object in increments of .5 degrees until it reaches 23.5 degrees, which it does, but my frameRate slows to a crawl.
Bad!
At one time I put a getTimer() device into the first listener to measure how fast it is being called, and I saw about 20ms without the rotation listener, and 200-250ms when the rotation listener was active.
Also of note, when the rotation listener reaches 23.5 degrees, and turns itself off, the calling of the frameAdvance listener stays the same (terribly slow).

Functions in my class:

    private function drawThis():void {
        removeEventListener(Event.ENTER_FRAME, wait4images);            
        for (var i:int = 0; i < shapeLoader.ShapeArr.length; i++) {
            addChild(shapeLoader.ShapeArr[i]);
        }

        //stage.addEventListener(Event.ENTER_FRAME, rotateme);
             //like this, it works quickly!

        stage.addEventListener(Event.ENTER_FRAME, rotateme);
             //like this, it is very slow!

        graphics.lineStyle(2,0xff0000)
        graphics.moveTo(0, -this.width / 2);
        graphics.lineTo(0, this.width / 2);
        addEventListener(Event.ENTER_FRAME, frameAdvance,false,0,true);
    }

    private function rotateme(e:Event):void{
        this.rotation += .5;
        if (this.rotation == 23.5) {
            stage.removeEventListener(Event.ENTER_FRAME, rotateme);
        }
    }

    private function frameAdvance(e:Event):void {
        frameNo += 1;   
        addChild(shapeLoader.ShapeArr[frameNo]);
        if (frameNo == 23) {
            frameNo = 0;
        }
    }

Any ideas/explainations/solutions for this problem out there?

Detect which movieclip you hit (AS3)

Im developing a game in AS3, And I ran into problem. I have the movieclip: ExitPoints. And inside this movieclip, there some other movieclips like: e_1, e_2, e_3 and e_4. When the player hit the ExitPoints movieclip, I want the game to trace which movieclip the player is standing on (e_1 or e_2 or e_3 or e_4).

I know I can make a code like:

if(player.hitTestObject(ExitPoint.e_1){
}

but I want to do it automaticlly with creating a lot of if statements. Any help?

vendredi 23 décembre 2016

Is there a simple method to match an array of bytes in an byte array?

I'm trying to check for a sequence of bytes in a byte array. Is there a method in the ByteArray class that works like indexOf()?

For example,

I'm trying to find out if a file is a PNG or JPG and so I want to check the byte array for that sequence of characters.

var PNG_INFO:Array = [89,50,4E,47];
var byteArray:ByteArray = new ByteArray();

var position:int = byteArray.indexOf(PNG_INFO);
var value:String = byteArray.readBytes(position, PNG_INFO.length);

if (value =="PNG") { trace("is png") }

I don't know if the code above is correct but I keep running into this problem where I have to find an array of bytes in a byte array. So my question is is there a method for what I'm looking for?

Resize Alternativa3D content with window resizing

I am working with legacy code and now I have some task: My Flash application view is resized when I resize window. And each internal sprites scales with window. But if I add some 3d component (extends Object3D class), window content stoped scale. If I decrease window size view choped of some parts instead scaling. When I delete this element window can scale again. Now I have task to window content scale always (including 3d element). Does anybody know: 1 - Is it base behavior of Alternativa3D library or we can switch off it? 2 - How can we switch iff or fix it?

Text not appearing in FlashDevelop project. But not throwing any errors either

This is my first time using FlashDevelop. I have buttons in a menu and a scoreboard. These all have a text field in them. In Adobe Animate, all worked fine, but in FlashDevelop, I understand I need to embed the fonts using strictly AS3 code, as there is no GUI library to drop them into.

I found this snippet but it only confirms (I think) that I've done it correctly, which obviously, I have not.

So here is my current permutation that does not throw any errors, and the game loads and runs fine (but there is no text anywhere) and the buttons work, but there is not text anywhere:

public class Main extends Sprite 
{

// ********** EMBEDDED ASSESTS **       
    [Embed(source = "/../lib/FATPIXEL.TTF", fontName = "fatPixel")] public static var myFatPixels:Class;

and then while creating a menu button:

// ********* BUTTONS **********
    private var button1:RoundButton= new RoundButton(60,30,gameReset,0xff386c,0x0,"1 Player");

Those are both in my main doc class. The following includes the constructor in my button class as well as the property declaration part inside the package:

    [Embed(source = "/../lib/AtariSmall.ttf", fontName = "smallAtari")] public var myAtariFont:Class;       
    public var tF:TextField = new TextField();
    private var myAtariFormat:TextFormat = new TextFormat(myFatPixels.fontName,25,0x00ffff);        

    var b:Sprite = new Sprite;
    var txt:String = new String();

    public function RoundButton(w:Number,h:Number,f:Function,colorA:uint,colorB:uint = 0x555599,text:String="button",dat2:Boolean = false):void {
        addChild(tF);
        tF.text = text;
        tF.embedFonts = true;
        tF.setTextFormat(myAtariFormat);
        tF.defaultTextFormat = myAtariFormat;
    }

Oh, and my .ttf files are here:

enter image description here

Can anyone see what is causing my problem? In Adobe Animate embedding was made simpler by having that option in a drop-down menu and having GUI access to the library. The syntax was notably different in that I was able to use the Font class whereas all sources I've found online show me to use the Class class? Here's what I mean:

Adobe Animate

var myFatPixels:Font = new FatPixels();

FlashDevelop

var myFatPixels:Class;

I think if I understood better the difference between these two lines of code I could figure out what I'm doing wrong.

So, I made a simple script to just at least try to get some text to show up. It works, but the font look like Times New Roman or some other system font, and not the font that it is supposed to look like. Here's my code that does this:

package
{
    import flash.display.Shape;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.*;

    /**
     * ...
     * @author Neal Davis
     */

    public class Main extends Sprite 
    {
        [Embed(source = "../lib/FATPIXEL.TTF", fontName = "fatPixel")] public static var myFatPixels:Class;
        private var tF:TextField = new TextField();
        private var myFont:Font = new myFatPixels();
        private var myAtariFormat:TextFormat = new TextFormat(myFatPixels.fontName,25,0xB6A4E3);    


        public function Main() 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            trace("hello world");
            var b:Sprite = new Sprite();
            addChild(b);
            b.addChild(tF);
            tF.defaultTextFormat = myAtariFormat;
            tF.text = "button";
            tF.setTextFormat(myAtariFormat);
        }

    }

}

The result being

TimeNewRomanFont

but it should look more like

fatPixelFont

jeudi 22 décembre 2016

Does ExternalInterface support dot notation access to a function owned by an object?

Does ExtenalInterface.call support dot access to functions?

I'm trying to write a wrapper class and not have all my functions on the window document so I've put them in my own class MyClass.MyFunction.

But does that work with external interface? Will this work:

var result:Object = ExtenalInterface.call("MyClass.MyFunction", "hello");

AS3 write string to an existing text file

I'm running my program on AIR. I want my game to save the high score to a text file so it can be stored when the program is closed. I've tried using filestreams, however I've found that the application directory is read only. Is there a better way to do this?

mercredi 21 décembre 2016

How to set up an app iicon for TVOS using AS3 ?

I have created an App for TVOS using AS3. But i am having trouble in setting up the app icon. Can anyone please suggest the steps on how to set up this icon using AS3.

Is there a way to send Apple users to the update page of the App store for my app in AS3

I'd like to add a button in my app where the user can click on it and it automatically opens the app store app with my app page.

Is there a way to do so in AS3 ?

Use of command line parameter in actionscript

Can a command line parameter be used in action script3, if yes how to pass and retrieve in the script. The syntax should be something like: myswf.swf param1

How to make a Grid, draw a shape in any of those cells and connect them together?

I have a very unique question regarding to my project

I have made a Grid including 25x15 cells using 3 classes:

First class named Tile.as and make cells for me:

package 
{
import flash.display.Shape;
import flash.display.Sprite;

public class Tile extends Sprite
{
    static const TILE_SIZE:int = 30;

    public function Tile() 
    {
        var tile:Shape=new Shape();
        tile.graphics.lineStyle(3, 0x000000);
        tile.graphics.drawRect(TILE_SIZE / 2, TILE_SIZE / 2, TILE_SIZE, TILE_SIZE);

        this.addChild(tile);
    }

 }

}

The next class named Grid.as to integrate all Tile together:

package 
{
import flash.display.Sprite;

public class Grid extends Sprite
{
    static const GRID_SIZE:int = 25;
    private var tileList:Vector.<Tile>;

    public function Grid() 
    {
        tileList = new Vector.<Tile>;

        for (var v:int = 0; v < GRID_SIZE; v++)
        {
            for (var z:int = 0; z < GRID_SIZE-15; z++)
            {
                var tile:Tile = new Tile();

                tile.x = v*Tile.TILE_SIZE;
                tile.y = z*Tile.TILE_SIZE;

                tileList.push(tile);

                this.addChild(tile);

                tile = null;

            }

        }

    }

}

}

And then I showed Grid in my Main.as class and show it in the out put:

public class Main extends Sprite 
{

    //grid
    private var grid:Grid;
    //

    public function Main() 
    {
        //show the grid
        grid = new Grid();
        grid.x = 10;
        grid.y = 10;
        this.addChild(grid);
        //  
    }
}

This is what I can see now: enter image description here

My question is that i want to add two objects in this grid. For example:

object A will be located in one cell (Tile)

object B will be located in another cell (Tile)

and then I want to connect these 2 objects together by highlighting the dimensions of the cells! this is an example of what I need to have:

enter image description here

Please ask me, if there is more explanation need to added!

And if I am going through the wrong way, please make me correct!

Thanks in advance!

Playing a movie clip to its full with mouse over

In Adobe Flash and ActionScript 3.0, I have a movieclip within a button. I want to play the entire movie clip upon mouse over. However, the movieclip plays only untill the mouse is over. I want to play the movie clip till the end if the mouse was there.

Any help is appreciated. I found a blog but, it is valid for AS2 only. This is what I want to do, but with AS3 : EchoEcho

I am a noob for flash and I dont know what to share for this kind of problem. I will provide anything that is needed for solving the problem

Thanks

mardi 20 décembre 2016

Value specified in SortField not being used by ArrayCollection Sort

I saw this earlier question (Flex arraycollection sorting not working) but it doesn't seem to pertain to the issue I am seeing.

I am trying to do a sort of an ArrayCollection using a custom compare function (using the example from here: Alphanumeric Sorting in AS3 )

The problem: It seems that the field name specified in my SortField instance is not being passed to the compare function – instead the objects themselves are. This seems wrong – but maybe I am misunderstanding (this question and the answers are a little confusing: Flex: Sort -- Writing a custom compareFunction?) – what is the point of specifying a field name in the SortField if it isn't going to be used?

A stripped down example is below. I am trying to sort a list of File instances. A trace statement in the compare function confirms that the File instance, not their name properties are being passed as arguments.

Do I need to customize the compare function? That is ** cough ** less that an optimal solution for reusable coding.


<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ift.tt/rYUnH9" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       creationComplete="windowedapplication1_creationCompleteHandler(event)">

    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.events.FlexEvent;

            import spark.collections.Sort;
            import spark.collections.SortField;

            import utils.AlphaNumericSort;

            protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
            {
                var directory:File = File.desktopDirectory.resolvePath("testFolder");

                if (directory.exists){

                    var collection:ArrayCollection;     
                    var obj:*;
                    var sort:Sort;
                    var sortField:SortField;

                    collection = new ArrayCollection(directory.getDirectoryListing());
                    sort = new Sort();
                    sortField = new SortField("name");
                    sortField.compareFunction = AlphaNumericSort.compare;
                    sort.fields = [sortField];
                    collection.sort = sort;
                    collection.refresh();

                    trace("---------AlphaNumericSort")
                    for each (obj in collection){
                        trace(obj.name);
                    }
                    trace(" ");
                }
            }

        ]]>
    </fx:Script>
</s:WindowedApplication>

AS3 Flash Game - AMF, XMLsockets

Hello dear community,

Certainly some of you know the game "Panfu", which ran over AS3 and an AMF server. XMLsockets were used for the Gameserver.

That's all I know about it. Now I would like, exactly like this game, to build my own Gameserver. Perhaps there is now a simple method for this, perhaps even a short help for the beginning.

I hope someone can help further. Thank you very much.

Is there a method that returns only the match or first variable match of a RegEx in ActionScript or null?

Is there a method yet that returns only a match and null if there is no match?

It may be a brain freeze but is there a method that just returns the match and null if not?

For example, if I want to just return the first variable or null otherwise:

var value:String = "image/png".toLowerCase();
var result:String = value.find(/image/(png|jpg|jpeg|gif)/);

if (result=="png") {
    // do something
}

I know there's replace and exec and match and they return arrays etc but I'm just looking for a method that returns my first match or null.

If there isn't this a function like this, I wish there was. How to god I wish there was.

lundi 19 décembre 2016

htmlloader - set/get parameter in js

In the loaded html page has a parameter: param = 0. For example, I want to change the parameter to: param = 1

I do: htmlloader.window.param = 1 The parameter is replaced, but I need to get changed the whole page. When I do this: document.documentElement.outerHTML in the JS script still remains: param = 0;

What could be the problem and whether it is possible to solve it? maybe it's a bug?

Publishing Adobe AIR iOS in Animate - Error creating files (arm64 error)

I am trying to publish an iOS app made in Adobe Animate, but I am getting an error (see image). I have not imported any ANEs, or done anything different from when i developed my earlier games, so I really have no idea on what to do..

Error message.

Any idea on how to fix this?

Thanks!

How would I check for a proper custom input of mm/dd/yyyy in actionscript 3?

What I mean is for ex. I have a DataField with editable="true" and format mm/dd/yyyy. Then lets say user typed in month mm section 13 which is not correct. How can I validate it as well as dd section and yyyy section and show a pop up when it's incorrect?

Here is what happening when apply button was clicked:

var newDate:Date = dfDate.selectedDate;
                var month:String = (newDate.month + 1) < 10 ? "0" + (newDate.month + 1).toString() : (newDate.month + 1).toString();
                var date:String = newDate.date < 10 ? "0" + newDate.date.toString() : newDate.date.toString();
                var year:Number = newDate.getFullYear();
                var dateString:String = month + "/" + date + "/" + year;

Button section:

<mx:FormItem id="itemDate">
                    <mx:DateField id="dfDate" yearNavigationEnabled="true" editable="true"/>
                </mx:FormItem>

Flex, Builder, etc. what are the differences?

I just downloaded Flex. Do I also need an IDE to compile my .as files? I don't see any executable files in the Flex SDK that I can load an .as into. Flash Builder looks like the "appropriate" choice but it costs moneys. If I were interested in paying moneys I would just use Adobe Animate like I did last year. Can someone sort me out?

Google Script for delimiting data

Hi I would like to know if there's a google script to delimit data that is in google spreadsheet. I have a data in google spreadsheet but I cannot use any script to delimit the text.

How can I get an image from url link and use it in HTML5 game, created in Flash?

I have my HTML5 game created in Flash and I am trying to get image from link. Let's say the image I want is at

http://ift.tt/2h26zBY.

In my game I already have a MovieClip with instance name pictureFromUrl. So how do I set its image source the image found at the mentioned example page?

this.parent.pictureFromUrl = ??

Change color when mouse over from pdf

I have a task: In my document I created some link. If I click it I go to some place from my document. And from time of click appears a highlight. I want to highlight appears from time mouse over. Whether exist some way to do it? I work with Flash, AS3 and AlivePdf library to create pdf (can work with PurePdf). Does anybody know how do it?

dimanche 18 décembre 2016

How would I make a "wrapping paddle" feature in my Pong game?

I'm making a Pong game in Actionscript 3 and I'm pretty much done it, however I need to create a feature where if the paddle passes the top of the screen it goes back to the bottom, and if it passes through the bottom it appears at the top. How would I create something like this?

Action Script 3 Visibility from a function

Here I have a simple Action Script 3 Code. tick1 is also a button and i defined its visibility to false at the start.

So What i want to happen is when I click the button, the tick to appear. What happens so far is it appears but disappear back instantly.

Also another question. Can I use a symbol other than a Button for tick1. If so how should I define it at the start.

Here is my code

import flash.events.MouseEvent;

    /*  */

    btnButter.addEventListener(MouseEvent.CLICK, butterHide);
    btnCoffee.addEventListener(MouseEvent.CLICK, coffeeHide);
    btnPflour.addEventListener(MouseEvent.CLICK, pFlourHide);


    var i:int = 0;
    tick1.visible = false;

    function butterHide (e:MouseEvent):void {

        //txtButter.visible = false
        btnButter.visible = false;
        tick1.visible = true;

    }

samedi 17 décembre 2016

Sending flash data to server using C/C++

Under my circumstances I need to be able to use raw sockets to manually craft IP/TCP/RTMP headers and so forth. However I do not know how flash applications communicate data back to servers. I need to know how to do this for a website called Tinychat. I guess in one, over simplified, sentence I need to be able to send data directly to the server. Obviously I don't really know what I'm talking about but I have a project in which I HAVE to do this and I'm freaking out because I don't even know where to begin or even how to explain my situation fully. If you close this question I completely understand. Any help WHATSOEVER would be absolutely awesome.

I need time limit help in ActionScript3.0

I am working on a time limit game, but when I load the game and it passes the time limit that is placed it reaches zero but it is not directed to the next scene where I have the game over .. this is the code that is placed

var tiempo:int;
var Duracion:int;


Duracion = 7;
tiempo = Duracion;
var timer:Timer = new Timer(1000,Duracion);
timer.addEventListener(TimerEvent.TIMER, tiempo2);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, fin)
timer.start();


function tiempo2(tiempoevent:TimerEvent):void
{
    trace(tiempo);

    tiempo--;

    time.text = tiempo.toString();

}

function fin(tiempoevent:TimerEvent):void
{
    var timer:Timer = tiempoevent.target as Timer;
    timer.removeEventListener(TimerEvent.TIMER, tiempo2)
    timer.removeEventListener(TimerEvent.TIMER, fin)


}

Como hago para que se direccione a la Escena de game over... lo estoy trabajando en animate cc...

Necesito ayuda en ActionScript3.0

Estoy trabajando en un juego de limite de tiempo, pero cuando cargo el juego y pasa el limite de tiempo que e colocado llega a cero pero no se direcciona a la siguiente escena donde tengo el game over.. este es el codigo que e colocado

var tiempo:int;
var Duracion:int;


Duracion = 7;
tiempo = Duracion;
var timer:Timer = new Timer(1000,Duracion);
timer.addEventListener(TimerEvent.TIMER, tiempo2);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, fin)
timer.start();


function tiempo2(tiempoevent:TimerEvent):void
{
    trace(tiempo);

    tiempo--;

    time.text = tiempo.toString();

}

function fin(tiempoevent:TimerEvent):void
{
    var timer:Timer = tiempoevent.target as Timer;
    timer.removeEventListener(TimerEvent.TIMER, tiempo2)
    timer.removeEventListener(TimerEvent.TIMER, fin)


}

Como hago para que se direccione a la Escena de game over... lo estoy trabajando en animate cc

Flash AS3 : Custom Sliders

I Am in need of some help making custom sliders, Sort of like the ones you would use for volume buttons, I have one but its not multi usable as soon as i add more than one the ones before stop working , and i dont think i can use local variables because i need to use event listeners for the scrubber to slide, All i am asking is if someone can please put a code for a multi usable slider with explanation on how its working so i can learn from it. i can show the code i am using right now but its probably useless

public function createSlider(x:Number, y:Number, parent:DisplayObjectContainer) : void {
        this.slider = new Sprite();
        this.slider.graphics.beginFill(0xFFFFFF);
        this.slider.graphics.drawCircle(x, y, 7);
        this.slider.graphics.endFill();
        this.bar = makeRoundedRect(x - 6, y - 6, 100, 11, 0xCCCCCC, 1, [10, 10, 10, 10]);
        parent.addChild(bar);
        parent.addChild(slider);

        this.slider.addEventListener(MouseEvent.MOUSE_OVER, sliderHover);
    }

    private function sliderHover(e:MouseEvent) : void 
    {
        this.slider.addEventListener(MouseEvent.MOUSE_DOWN, sliderDown);
    }
    private function sliderDown(e:MouseEvent) : void {
        this.slider.addEventListener(MouseEvent.MOUSE_MOVE, sliderMove);
        this.slider.addEventListener(MouseEvent.MOUSE_UP, sliderDone);
        this.slider.addEventListener(MouseEvent.MOUSE_OUT, sliderDone);
    }

    private function sliderMove(e:MouseEvent) : void {
        this.slider.addEventListener(MouseEvent.MOUSE_DOWN, sliderDown);
        this.slider.removeEventListener(MouseEvent.MOUSE_MOVE, sliderMove);
        this.slider.startDrag(false, new Rectangle(0, slider.y, 90, 0));

    }
    private function sliderDone(e:MouseEvent) : void {
        this.temp_mouseCurX = Math.abs(this.slider.x + 10);
        trace(this.temp_mouseCurX);
        this.slider.stopDrag();
    }

its using a private variable which i know shouldnt be good for what i am trying to do , Any help is appreciated, And just comment and let me know if you need more information i will try to put as much as possible

vendredi 16 décembre 2016

How to save the position of an object in as3 and then load it when the game opens again?

Just like the game callen Pet Society or Party town . The furniture's position should be saved.

hittestobject multiple functions with Drag and drop

I have troubles making this code functionnal, i am pretty new to coding and learn everyday, so sorry if this question looks stupid.

Here's where I am so far :

  • a1 is a drag and drop object
  • a2 is an area, which when a1 is dropped on it, add the value 5 on a textfield
  • a3 is an area, which when a1 is dropped on it, substract the value 5 on a textfield

a1 start in the a3 area, when I drag a1 to a2, it shows 5, if I drag back to a3, it shows 0, so it's working as intended


Now what I struggle with :

  • a code that don't add 5 if I move a1 to a2, when a1 is ALREADY on a2.
  • a code that don't substract 5 if I move a1 to a3, when a1 is ALREADY on a3.

here's my code :

var myTextBox:TextField = new TextField();  

var myTextBox2:TextField = new TextField(); 
addChild(myTextBox2); 
myTextBox2.width = 200;    
myTextBox2.height = 100;    
myTextBox2.x = 100;    
myTextBox2.y = 20; 

a1.addEventListener(MouseEvent.MOUSE_DOWN, drag);
stage.addEventListener(MouseEvent.MOUSE_UP, drop);

function drag(e:MouseEvent):void
{
e.target.startDrag();
}

function drop(e:MouseEvent):void
{
stopDrag();
if (a1.hitTestObject(a2))
{
    myTextBox.text = "5";
    var r:String=String(uint(myTextBox.text)+uint(myTextBox2.text));
    myTextBox2.text=r;
}
if (a1.hitTestObject(a3))
{
    myTextBox.text = "5";
    var r2:String=String(uint(myTextBox2.text)-uint(myTextBox.text));
    myTextBox2.text=r2;
}

else
{
    trace("No collision.");
}
}

I don't think it's too complicated, but I don't have the knowledge yet to make it work, any assistance would be greatly appreciated ! thanks!

how can i make a variable to save the selected color from colorPicker component as3

i just asking if i make a colorPicker component in adobeAnimate how can i save the current selected color to a variable that i will use it to change a mc color ?

Component Parameters

JavaScript Output...to Flash; Not the Same...? [on hold]

I have a Flash app that can receive data and trace it fine from the second example but obviously there's more functionality with the first one. The first one can connect and receive data but I can't for the life of me get flash to pickup any response. I know it's setup correctly, since one of the servers burps out input without a problem. Honestly I think I'm gonna try & use socket io at this point but I'd like to know why this doesn't work.

I'm guessing it's the client object for some reason at the top of the first server, would just like to know for curiousity/future reference, who knows maybe someone will google something similar

Server 1 (JavaScript) : http://ift.tt/2gShcsJ

Server 2 (AS3 / Flash) : http://ift.tt/2h8GQp2

Edit: I'm wondering why these two node servers output different data...how is that off topic...?

Possible solution: For those with the same problem, use socket.pipe(socket) and the data starts showing up on the first client just like the second one. Still don't know why so I'm off to research.

jeudi 15 décembre 2016

flex/as3 - How to force BitmapData smooth not to draw

I'm gonna force a BitmapData smooth.

but I can't do BitmapData.draw() because the performance of application.

If I draw Bitmap, the application slow down to next step. (this is on flex mobile)

so I need how to force bitmapData smooth without redraw bitmapData.

(also, I can't use Bitmap(bitmapData).smoothing)

what can I do for this?

help me please.

Why am I suddenly unable to refresh idToken with Firebase REST API in an AS3 AIR Android Project.?

I had integrated FIREBASE Authentication and Storage using this guide and it was working just fine. Yesterday suddenly, I am unable to get to refresh the token. Every time I call the refreshToken(idToken) method, I get a 400:Invalid Id Token error.

I didn't change the code, I was testing the app one day and it was working fine, I checked that same app the next day and it wasnt working. I have no idea what to do. Any help is greatly appreciated.

Here is the code I am using to refresh the token:

    private function refreshToken(idToken:String):void
    {
        trace("refreshing id token");
        var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");

        var myObject:Object = new Object();
        myObject.grant_type = "authorization_code";
        myObject.code = idToken;

        var request:URLRequest = new URLRequest("http://ift.tt/2egrqjc"+FIREBASE_API_KEY);
        request.method = URLRequestMethod.POST;
        request.data = JSON.stringify(myObject);
        request.requestHeaders.push(header);

        var loader:URLLoader = new URLLoader();
        loader.addEventListener(flash.events.Event.COMPLETE, refreshTokenLoaded);
        loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
        loader.load(request);   
    }

Skip preloader when load swf file in actionscript3

I want to skip preloader in external swf file becuse when i load swf file, my project stuck in preloader and does not show swf master content!! Please help!!

Adobe Animate CC dynamic text null error

I have got this error

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

I just can't seems to display my score on the dynamic text box that I created that I named as "scoretext"

this is my code

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


addEventListener(Event.ENTER_FRAME, game);
addEventListener(MouseEvent.CLICK, onClick);

var score:int = 0;
var high:int = 0;

const gravity:Number = 2;
const force: Number = 30;
const lyfe: Number = 100;
var yspeed: Number = 249;
var life: Number = 0;

function onClick(event:MouseEvent):void
{
     //just testing if mouse input is detected
     trace("The event handler works!");
}





//game main loop
function game(event: Event) {


    score = 0;
    life = lyfe;
    yspeed = yspeed + gravity;
    player.y = yspeed;

    if(player.y - player.height/2 < 0)
            player.y = player.height/2;

    for (var i = 0; i < numChildren; i++) {


    //test if mons hit player
    if (mons.hitTestObject(player)){
        life = life - 10;

        trace("hit");
    }
    //test if starz hit player
    if (starz.hitTestObject(player)){

       //I believe this is the part where it gets the error
       //this is my scoretext dynamic text box to display the score
        scoretext.text = score.toString();
        ++score;

    }


}
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler_2);

function fl_KeyboardDownHandler_2(event:KeyboardEvent):void
{
if(event.keyCode == 32){

    yspeed = yspeed - force;
    trace("Key Code Pressed: " + event.keyCode);
    player.gotoAndPlay(41);
}

}

Adobe flash professional CC gotoAndPlay bug

First of all, hello.

I have to develop a simple game in flash, usign HTML5 Canvas and JavaScript. The game, however poor, is pretty much implemented. My problem is, that after you play the game, it shows a try again button, designed to go back to frame 1. When i click the button it goes to frame 1 and returns to frame 25. Any ideas?

This is my timeline

The last frame has this code:

var root = this;
this.stop();
this.tryAgain_btn.addEventListener("click", mouseClickHandler);
function mouseClickHandler(e) {
     root.gotoAndPlay(0);
};

And frame one has this code:

var self = this;
this.stop();    
this.play_btn.addEventListener("click", go);

function go()
{
    self.gotoAndPlay(1);
}

Any ideas on how to solve this? Thank you.

mercredi 14 décembre 2016

How can i install flash builder 4.7 in Eclipse X64 folder(dropins) (version 4.6) its impossible?

  • (in my Eclipse 4.6 X64 eclipseproduct : name=Eclipse Platform id=org.eclipse.platform version=3.7.0

    And i'm using flash builder 4.7

    Thank you guys .)

Proper term for 'if (object)' as a non-null test?

In ActionScript 3, you can check if a value exists like this:

if (object) {
    trace("This object is not null, undefined, or empty!")
}

I frequently use this as a shorthand for if (object != null)

Is there a proper term for evaluating objects for null in this fashion? I suppose it's a matter of the Boolean typecasting rules for the language but I'm not sure if there's a name for the resulting syntax.

Bitwise in a client - server scenario miscalculating

I have been tasked with creating a server for a client. I have all of the clients' code, so using it, I must create a server.

The client has a particular piece of code in a function called readInt(num1); return num1 << 24 | num1 << 16 | num1 << 8 | num1, and I can't haggle with it.

I tried what comes to mind first - just reverse it, right? If the int needs to be 3, do 3 << 24, but no yield.

My mind doesn't work well mathematically, and I'm not a good problem solver, so if I want, say 3 on the server to read as 3 on the client, what formula would I use server-side to achieve this?

The client is in Adobe ActionScript 3, and the server in Python 2.7.12.

actionscript 3 presentation onclick without buttons

Is there a possibility to go to the next slide with left click, I can only see buttons in the default one right to go forward and left to go backwards. is this possible with the left click to go forward? without any buttons?

This is the default code:

stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_changeSlide);
function fl_changeSlide(evt:KeyboardEvent):void
{
    if(evt.keyCode == 37) // LEFT
    {
    gotoAndStop(this.currentFrame-1);
    }
    else if (evt.keyCode == 39 || evt.keyCode == 32) // RIGHT OR SPACE
    { 
        gotoAndStop(this.currentFrame+1);
    }
}stop();

When an Adobe AIR app requests a resource from the server what shows as user agent?

When a browser like Chrome makes a request for a web page or image like a gravatar icon the server receives the userAgent information like so:

"Chrome/2.0 AppleWebKit/400.1.1 (KHTML, like Gecko)"

But if an Adobe AIR app makes a request for an image in the Image component what does the server receive? Is the same as a URLRequest?

"Chrome/2.0 AppleWebKit/400.1.1 (KHTML, like Gecko) AdobeAIR/3.0"

Background:
My AIR app shows Gravatar icon for the user and recently it stopped working. I'm wondering if it's gravatar is denying calls from user agents it doesn't recognize.

I've tried changing the userAgent to test the theory and it's throwing an error:

// 1195: Attempted access of inaccessible method userAgent through a reference with static type Class.
URLRequestDefaults.userAgent("chrome");

Update:
It looks like I need to set the user agent as a property and not a method. Was referring to this forum post. So I can change that might fix the gravatar issue but not answer how Adobe AIR apps appear to the server.

Simple autocomplete with Ace Editor in AS3?

I'm working in XML and I'd like to provide autocomplete suggestions for the attributes for specific node types using AS3.

For example, if the user is has a cursor in the following node:

 <s:Button label="Hello World"/>

I'd like autocomplete to show "width, height, x, y".

I'm trying to get the node name and namespace and then give the editor a list of attributes that should appear in autocomplete.

I found similar questions but those are using a service call and a few that are out dated. I may delete this question if it is a duplicate.

Ace Editor for AS3 here.

How to sychronously get the width and height from a base64 string of image data?

Is there a way to get an image width and height from a base64 encoded image data synchronously? Possibly by header information.

I must make this extremely clear. I'm not interested in async methods. Please move on if you want to know reasons why async won't work. Don't even comment.

Here is my example code to encode my data. Encoding is synchronous. I'm using this call:

var base64ImageData:String = DisplayObjectUtils.getBase64ImageDataString(displayObject, DisplayObjectUtils.PNG, null, true);

Here is my code to decode my data. The only method I've found in AS3 to decode is asynchronous. I'm using this call:

var bitmapData:BitmapData = DisplayObjectUtils.getBitmapDataFromBase64(bitmapDataString);

Let me repeat, I'm looking for a synchronous action. It cannot be asynchronous.

More information:
I'm working in ActionScript3 which is a sibling to JavaScript. If it works in JavaScript it most likely works in AS3. But I cannot work with the dom. No adding images to the dom and checking values.

Helpful hacks:
If it's possible to add width and height into the base64 stream and then get it later that will work as well.

ActionScript3, dropping on stage not working after using MouseEnabled

I'm targing to do do a BattleShip Flash game using ACtionScript 3. 1- I draw a grid (class: com.Battleship.grid) using a gridCell:movieClip (class: com.battleship.GridCell) 2- I draw a Ship (class: com.battleship.Bateau)

My objective is when I drag the ship to the grid the alpha cell under the mouse changes, and if i drop: 1- if the droptarget is a gridCell the ship takes place (works fine) 2- if the droptarget is stage the ship return to originPosition (not working) My problem: is after I used MouseEnabled= false, the ship can drop on the grid but not on the stage and still dragging. here is e my code:

var grid:Grid = new Grid(10,new Point(20,20));
var b1:Bateau = new Bateau();
b1.x = 490;
b1.y = 300;
b1.originPos = new Point(b1.x,b1.y);    
addChild(b1)
addChild(grid);

package com.battleship  {

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


    public class Bateau extends MovieClip {

        private var _originPos:Point;

        public function Bateau() {
            originPos = new Point();
            buttonMode = true;
            addEventListener(MouseEvent.MOUSE_DOWN, onDrag);

        }
        protected function onDrag(e:MouseEvent):void
        {
            e.currentTarget.parent.addChild(e.currentTarget);
            e.currentTarget.startDrag();
            e.currentTarget.mouseEnabled = false;
            //e.currentTarget.mouseChildren = false;
            addEventListener(MouseEvent.MOUSE_UP, onDrop);
            parent.addEventListener(MouseEvent.MOUSE_UP, onDrop);
        }
        protected function onDrop(e:MouseEvent):void
        {
            e.currentTarget.mouseEnabled = true;
            e.currentTarget.mouseChildren = true;
            e.currentTarget.stopDrag();
            if(dropTarget == null){
                x = originPos.x;
                y = originPos.y;
            }else{
                trace(e.currentTarget.name);
                if(dropTarget.parent is GridCell)
                {
                    x = dropTarget.parent.x+20;
                    y = dropTarget.parent.y;
                }
            }           
        }
        public function get originPos():Point
        {
            return _originPos;
        }
        public function set originPos(originPos:Point):void
        {
            _originPos = originPos;
        }
    }

}

    package com.battleship  {

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


    public class GridCell extends MovieClip {
        private var _row:int;
        private var _col:int;
        private var _val:int;

        public function GridCell()
        {
            addEventListener(MouseEvent.CLICK,onClick);
            addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
            addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
        }

        public function onClick(e:MouseEvent)
        {
            //trace("(" + e.currentTarget.row+ ", " + e.currentTarget.col + ")");
            trace(e.currentTarget.name);
        }

        public function onMouseOver(e:MouseEvent)
        {
            alpha = 0.6;
        }

        public function onMouseOut(e:MouseEvent)
        {
            alpha = 1;
        }

        public function get row():int
        {
            return _row;
        }
        public function set row(row:int):void
        {
            _row = row;
        }
        public function get col():int
        {
            return _col;
        }
        public function set col(col:int):void
        {
            _col = col;
        }
        public function get val():int
        {
            return _val;
        }
        public function set val(val:int):void
        {
            _val = val;
        }
    }

}

package com.battleship  {
    import flash.geom.Point;
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class Grid extends Sprite {      
        private var _size:int;
        private var _position:Point;

        public function Grid(size:int,position:Point):void
        {
            _size = size;
            _position = position;
            var gridCells:Array = new Array(size,size);
            var i,j:int;
            for(i=0;i<size;i++)
            {
                gridCells[i] = new Array();
                for(j=0;j<size;j++)
                {
                    var cell:GridCell = new GridCell();
                    cell.row = j+1;
                    cell.col = i+1;
                    cell.x = this.position.x + cell.width * (i+1);
                    cell.y = this.position.x + cell.height * (j+1);
                    cell.name = "cell" + (j+1) + (i+1);
                    //cell.addEventListener(MouseEvent.CLICK,onClick);
                    gridCells[i][j] = cell;
                    this.addChild(gridCells[i][j]);
                }

            }
        }

        public function get size():int
        {
            return _size;
        }
        public function set size(size:int):void
        {
            _size = size;
        }
        public function get position():Point
        {
            return _position;
        }
        public function set position(position:Point):void
        {
            _position = position;
        }

    }

}

mardi 13 décembre 2016

AS3 object passed as e.target does not match identical object passed through its array index

im designing an inventory system. right now, i need to test whether or not an item is in the inventory in order for the stage to know whether to instantiate that item in the particular level or not.

i add the items to the levels in groups, so this code is located within an array loop which "unloads" the "pack" of items corresponding to each level.

if (inv.indexOf(group[i]) == -1) {
    //add item + item functionality
}

this method works when i add the item to the inventory such as this:

inv.push(group[i]);
if (inv.indexOf(group[i]) == -1) {
    //add item + item functionality
}

but that doesn't work, because why would i add an item to the inventory without the user collecting it first? so the code is actually structured as so:

            if (inv.indexOf(group[i]) == -1) {

                //if item is not in inventory, add to stage
                addChild(group[i]);

                //when a user clicks this (any) item,
                group[i].addEventListener(MouseEvent.CLICK, function itemFunctionality(e:MouseEvent){

                    //target item clicked
                    var item = e.target;
                    //add the item to the inventory
                    inv.push(item);
                    //sidenote: if i were to check inv.indexOf(item) here, i 
                    //would get a positive index. unfortunately,
                    //i cant check whether the item is in the inventory
                    //after its already been added to the level...

                    item.removeEventListener(MouseEvent.CLICK, itemFunctionality);
            });
            }

the problem is when you leave and come back to the level, the items you already collected re-instantiate.

if you collect an item again, the inventory adds a copy of the item you already collected.

the inv.indexOf(group[i]) checker doesn't understand that when the array loop reaches the corresponding, item group[i] == the object added to the inventory through inv.push(item) or in other words inv.push(e.target) (which, of course, i couldnt write directly into the code)...

when i trace whats inside of static array inv, what group[i] is within the array loop, or what e.target is, they all output the same type of item, "[object itemName]", signifying that the indexOf check SHOULD match up.

what the heck!!!

lundi 12 décembre 2016

Air Map API for 2017

It's Dec 2016. The Adobe flash & Air API has been deprecated, and I have a major project coming up that relies heavily on maps. What should I do to make it work on AIR?

Thinking of Google Maps API JavaScript + Mobile web view. A little worried about power consumption or ram issues on lower performance smartphones.

Is that my best bet? Or is there one out there that still works for AIR?

How can I set a public variable using getChildIndex in as3?

I am new to stackoverflow, and this is my first question.

I recently started programming with as3, so I don't know too much about as3 yet, but...

I was coding a very simple program that lets you move around a circle, with also a rectangle in the stage. I wanted to make the circle get in front of the rectangle while you are dragging it, but when you released the mouse, the circle would be sent back.

The thing is, that I don't know how to set a public variable using the getChildIndex method. I don't really care about the rest of the code. I'm mainly interested in how can I make the getChildIndex method work with a public variable.

Here is my code:

package code
{

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


    public class Main extends MovieClip
    {           
        public var myCircleIndex:int = getChildIndex(myCircle);

        public function Main()
        {
            myCircle.addEventListener(MouseEvent.MOUSE_DOWN, mouseClicking);
            stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
        }

        public function mouseClicking(e:MouseEvent): void
        {
            myCircle.startDrag();
            setChildIndex(myCircle, numChildren-1);
        }

        public function mouseReleased(e:MouseEvent): void
        {
            myCircle.stopDrag();
            setChildIndex(myCircle, myCircleIndex);
        }
    }
}

I'm using an instance ("myCircle") that I created directly in the stage as a movie clip.

The problem is in the public var I set at the beginning, it doesn't let me get the child index of myCircle, but if I put the same line inside a function, it works.
I know I could directly put the index number of myCircle in the last line (and erasing the public var myCircleIndex), but I figured out that there would be a way of using the getChildIndex for a public var in a class.

I wish you could tell me how to use the getChildIndex in a public variable inside a class, don't need to worry about the rest.

Thank you for reading,
~m5

dimanche 11 décembre 2016

AS3 Air Native Extension com.distriq.Core conflits with other ANEs

I'm facing the issue with the com.distriq.Core ANE, it's conflicting with my other ANEs (I know it when I remove it from app packaging, but after include this ANE, Flash Builder was failed to build).

Here is the error message:

Error occurred while packaging the application:

dx tool failed:
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lcom/adobe/air/ActivityResultCallback;
    at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:122)
    at com.android.dx.dex.file.DexFile.add(DexFile.java:161)
    at com.android.dx.command.dexer.Main.processClass(Main.java:737)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:678)
    at com.android.dx.command.dexer.Main.access$300(Main.java:83)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:607)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:637)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:511)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:281)
    at com.android.dx.command.dexer.Main.run(Main.java:247)
    at com.android.dx.command.dexer.Main.main(Main.java:215)
    at com.android.dx.command.Main.main(Main.java:106)
1 error; aborting

So I'm asking for an advise, what should I do now?

Much appreciated !

TypeError: Error #1010: A term is undefined and has no properties.

When I test my project, the error report was shown. TypeError: Error #1010: A term is undefined and has no properties. at Game_Gerak_Parabola_Scene1_fla::MainTimeline/Setting_awal()[Game_Gerak_Parabola_Scene1_fla.MainTimeline::frame1:77]

here is the code,

function Setting_awal()

{

    Xo = bola.x;
    Yo = bola.y;
    txt_Dx.text = "ΔX = "+(target.x-bola.x)/100+" m";
    txt_Dy.text = "ΔY = "+(bola.y-target.y)/100+" m";
    karet1.x = Xo-10;
    karet1.y = Yo;
    karet2.x = Xo+10;
    karet2.y = Yo;
    MovieClip(root).karet1.graphic.clear();
    MovieClip(root).karet1.graphic.lineStyle(15, 0x003300, 100);
    MovieClip(root).karet1.graphic.moveTo(0, 0);
    MovieClip(root).karet1.graphic.lineTo(-2, 0);
    MovieClip(root).karet2.graphic.clear();
    MovieClip(root).karet2.graphic.lineStyle(15, 0x005500, 100);
    MovieClip(root).karet2.graphic.moveTo(0, 0);
    MovieClip(root).karet2.graphic.lineTo(-15, 0);
    MovieClip(root).garis1.graphic.clear();
    MovieClip(root).garis2.graphic.clear();
    MovieClip(root).lingkaran.graphic.clear();
    mc_var.x = 100000;

}

Removing Color from Sprite ActionScript

My project loads SWF files using the Loader class, and then loads Sprite objects from those child files. Each sprite has a specific green color, and I want to substitute all pixels of one color for transparent ones.

I can re-compile these Sprites as objects of the BitmapData class, to simplify things, but I'm looking for any way that avoids operating the objects pixel-by-pixel. I'm guessing that I can use some kind of bitmap filter, but I'm just not familiar enough with ActionScript to know specifics.

How to detect diagonal swipe gesture in as3 for android

How do I detect a diagonal swipe gesture which will enable a character jump over the obstacle?

Send all instances of a container BEHIND everything else?

Found this topic: AS3 setChildIndex to front and I have no idea why, but for some weirdly illogical reason I can edit other peoples' posts but I can't comment on other peoples' question answers... what? Anyway, the question here is similar to that of this, just that I'm trying to accomplish the exact opposite, but since I can't comment on it and need goddamn 50 reputation, I had to ask a new question.

Anyway, to the problem. "addChildAt" doesn't work for me when I'm setting the container behind everything else or something along the lines. And as for stars themselves, I can't send them back anymore than layer 0 for some odd reason (it'll give me error 2006, stating "The supplied index is out of bounds"). Here's the code:

starsSpawn function:

var starContainer:MovieClip = new MovieClip();
addChildAt(starContainer, 20);

starContainer code:

function starsSpawn()
{
    for(var i:int= 0; i < 30; i++)
    {
        var newStar = new starCode();
        var scaleXY = Math.random()*(2)+0.1;
        newStar.width = scaleXY;
        newStar.height = scaleXY;
        var positionX:Number = Math.random()*(stage.stageWidth + (1* newStar.width));
        var randomY:Number = Math.random()*(stage.stageHeight - newStar.height);
        newStar.x = positionX;
        newStar.y = randomY;
        starContainer.addChild(newStar);
    }
}

Essentially how it works is that a container is set up and the for loop creates 30 stars, each with the outlined code.

How to convert string and/or array fields to movie clips AS3

My question is that how we can convert a string to a movie clip OR How to convert each field of an array to a movie clip.

For example:

var days:Array = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");

and I want "Sun" to become a movie clip Or

var str:String;
for (var i=0; i<days.length; i++)
{
    str = days[i];
    //and then I need to convert str to become a movie clip each time
}

Thanks for your help in advance.

How to convert different line of a dynamic text box to Movie clip in AS3

I have a question regarding to my project which is How to convert different line of a dynamic text box to Movie clip in AS3?

Actually, I have an text file named test.txt. For instance:

It consists of: Sun;Mon;Tue;Wed;Thu;Fri;Sat;

and then I want to put all of them into an array and then a string to show them in the dynamic text Box called text_txt.

I have different objects in my library. If we see "sun;" in the first line, the first object will be shown in a specific area on my movie clip.

The question is here:

Fist: if I have different texts in my first line. for instance "today is sun;". how to find that the "sun" is in this line???

Second: How to convert different line of a dynamic text box to Movie clip. So, is user click on the "mc.obj01", the first line in the dynamic textbox will become bigger???

Thanks for your time and help in advance.

import flash.events.MouseEvent;

var flag:int = 0;


//load the txt file
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
myTextLoader.load(new URLRequest("test.txt"));

//when the scene loads, all the info from txt file shown into the dynamic text;
function onLoaded(e:Event):void
{
//put all the info into array
var days:Array = e.target.data.split(/\n/);

var str:String;
//show them in the dynamic text
for (var i=0; i<days.length; i++)
{
    str = days[i];
    text_txt.appendText(str + "\n");

    //if one text founded, do somethind and shoe an objectinthe output;
    switch (str)
    {
        case "sun;\r" :
            var obj01:Show = new Show();
            mc.addChild(obj01);
            obj01.x = -200;
            obj01.y = -15;
            break;

        default :
            trace("None of the above were met");
    }
}

obj01.buttonMode = true;


//if the object clicked then something must be happend to the first line in the dynamic text box
obj01.addEventListener(MouseEvent.CLICK, firstLine);
function firstLine(e:MouseEvent):void
{
    flag = 1;

    switch (flag)
    {
        case 1 :
            trace("Clicked!");
            //the first line in the text box should get a different background and become more bigger
            //Do I need to convert the first line to a movieclip? OR I need to do in another way?! 
            break;

        default :
            trace("None");
    }
}

}

Adobe Animate Starling Error

I have created hungryherogame (recreate) in adobe animate using starling framework.. download from this address below :

( http://ift.tt/2goqXcI )

Its made an error --> Call to a possibly undefined method fromBitmap through a reference with static type Class.

Thanks and best regards.

How to get class definition from prefix and node name using SchemaTypeRegistry and SchemaManager?

I'm trying to register class definitions dynamically so that I can parse an XML document later get the correct class in the correct namespace.

I'm able to register the types using an instance or qualified class name string using SchemaTypeRegistry:

typeRegistry = SchemaTypeRegistry.getInstance();

var windowedApplicationQName:QName = new QName(MXMLDocumentConstants.sparkNamespaceURI, "WindowedApplication");
//typeRegistry.registerClass(windowedApplicationQName, WindowedApplication);
typeRegistry.registerClass(windowedApplicationQName, "spark.components::WindowedApplication");

I can then get the class and create an instance of it easily enough:

var className:Object = typeRegistry.getClass(windowedApplicationQName);
var classInstance:Object;
classInstance

= new className();

But later on, I'm inside a text document, don't ask why, OK I'm in an XML text editor, and I can get the XML node name, in this case that value is "s:WindowedApplication".

So now when I'm trying to register known namespace URI's and I'm doing that with the SchemaManager:

schemaManager = new SchemaManager();
schemaManager.addNamespaces({s:MXMLDocumentConstants.sparkNamespace});
var qname:QName = schemaManager.getQNameForPrefixedName("s:WindowedApplication");

This is great because I can get the QName object and then I can search for it using the type registry like so:

qname = schemaManager.getQNameForPrefixedName("s:WindowedApplication");
var classObject:Object = typeRegistry.getClass(qname);

Problem 1: If the prefix isn't registered in the schemaManager or there is no prefix the schemaManager throws an error. This is because it is expecting a schema but the data types are dynamic so there isn't one.

Problem 2: The type registry has no knowledge of the namespace prefixes and the schema manager has no knowledge of class definitions of QNames. This leads me to believe there is a piece I'm missing.

If nothing else I could extend either class and add code from either class to connect the class definitions with the namespace and namespace prefixes. But again, there seems like there's a piece missing.

So pretending I didn't hack a fragile, easily broken system is there an official or better method to store class definitions, their namespaces and prefixes?

samedi 10 décembre 2016

Read a string in AS3

I have a question regarding to my project which is how to read a string in AS3.

Actually, I have an text file named test.txt. For instance:

It consists of: Sun,Mon,Tue,Wed,Thu,Fri,Sat

and then I want to put all of them into an array and then a string to show them in the dynamic text Box called text_txt:

var myTextLoader:URLLoader = new URLLoader();

myTextLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void
{
 var days:Array = e.target.data.split(/\n/);
 var str:String;
 stage.addEventListener(MouseEvent.CLICK, arrayToString);

 function arrayToString(e:MouseEvent):void
  {
    for (var i=0; i<days.length; i++)
    {
        str = days.join("");
        text_txt.text = str + "\n" + ";"; //it does not work here
    }
 }
}

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

BUT IT DOES NOT show them in different line and then put a ";" at the end of each line !

I can make it to show them in different line, but I need to put them in different line in txt file and also I still do not get the ";" at the end of each line unless put it in the next file also at the end of each line.

And then I want to read the string and show an object from my library based on each word or line. for example:

//I  do not know how to write it or do we have a function to read a string and devide it to the words after each space or line 
if (str.string="sun"){
 show(obj01);
}
if (str.string="mon"){
 show(obj02);
}

I hope I can get the answer for this question. Please inform me if you can not get the concept of the last part. I will try to explain it more until you can help me. Thanks in advance

Importing whole .swf file in Haxe OpenFL

My problem is that I try to import whole swf file (not just as3 class) into my OpenFL project. I don't know the sourcecode or anything, but looks like I don't have to. Documentation says that I can import whole swf without knowing class names. However i got an error "NULL OBJECT REFERENCE" after compiling the project and than it terminates. I just need a working code sample to find my mistakes. Thanks.

how to getTime in actionscript 3

i need your help. I a beginner in actionscript 3 and I want to convert code form as2 to as3. I want you to chek that mycode is corectly. can you help me, please

here is the code,

timeFaktor = 4;

function timeReset() {
    delete curretnTime;
    delete showtTime;
    currentTime = new Date();
    showTime = new Date();
    startingTime = false;
    pauseTime = 0;
    txt_Time.text = "t = "+0+" s";
}

function moveTime() {
    delete currentTime;
    currentTime = new Date();
    if (!startingTime) {
        starTime = currentTime.getTime();
        startingTime= true;
    }
    newTime = Number(currentTime.getTime()-starTimeMulai)+Number(pauseTime);
    secon = newSecon/1000;
    time = (Math.round(detik*100))/100;
    txt_time.text = "t = "+time+" s";
}

How do I stop automatic stretching of the other axis for instances when stretching one of its axis?

When applying code for a laser weapon projectile (an instance of the laser beam itself) which would enable the laser to to act similarly to that of a real one, I had everything working great... except for the fact that the projectile kept stretching in the y axis as well as the x axis, instead of just the x axis. Now, I've found out that something like scaleMode needs to be disabled, but the best I've found is a line of code that goes like "stage.scaleMode = StageScaleMode.NO_SCALE;", which is meant for the stage and not instances themselves and if I tried to apply something like this for an ADDED event within the laser beam's class code I get error 1120 saying . Here is the code I think is necessary to present here from the beam's class:

package
{
    import flash.display.MovieClip;
    import flash.events.*;
    public class weapon3projectileCode extends MovieClip
    {
        private var _root:Object;
        public function weapon3projectileCode()
        {
            addEventListener(Event.ADDED, beginClass);
        }
        private function beginClass(event:Event):void
        {
            _root = MovieClip(root);
            this.scaleMode = StageScaleMode.NO_SCALE;
            this.scaleX = .25;
            this.scaleY = .2;
        }
        private function entFrame(event:Event):void
        {
            if (_root.gamePaused == false)
            {
                x += speed;
                if (stretchWhile < stretchTill)
                {
                    this.width += 25;
                    this.x = _root.playerShip.x;
                    this.y = _root.playerShip.y;
                }
                else if (stretchWhile < shrinkTill)
                {
                    this.width -= 25;
                }
                else if (stretchWhile >= shrinkTill)
                {
                    this.width = .25;
                    removeEventListener(Event.ENTER_FRAME, entFrame);
                    _root.projectilePlayerContainer.removeChild(this);
                }
                stretchWhile ++;
                if(this.x > (stage.width+ this.width))
                {
                    removeEventListener(Event.ENTER_FRAME, entFrame);
                    _root.projectilePlayerContainer.removeChild(this);
                }
            }
            if (_root.removeProjectiles == true)
            {
                removeEventListener(Event.ENTER_FRAME, entFrame);
                _root.projectilePlayerContainer.removeChild(this);
            }
        }
    }
}

Keeps saying "a term is undefined" when it is actually defined?

So, from what I've read and understood, the 1010 error, where it says "a term is undefined and has no properties" means that some variable has not been declared or it has been declared but doesn't have any properties to begin with. Is that correct? If so, then why does it give me the error at "if (_root.removeProjectiles == true)" from this class code:

package
{
    import flash.display.MovieClip;
    import flash.events.*;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    public class weapon1projectileCode extends MovieClip
    {
        private var _root:Object;
        private var speed:int = 10;
        public function weapon1projectileCode()
        {
            addEventListener(Event.ADDED, beginClass);
            addEventListener(Event.ENTER_FRAME, entFrame);
            playSound();
        }
        private function beginClass(event:Event):void
        {
            _root = MovieClip(root);
            this.scaleX = .25;
            this.scaleY = .2;
        }
        private function playSound():void
        {
            var sndFire:weapon1projectile_sound;
            var sndFireChannel: SoundChannel;
            sndFire = new weapon1projectile_sound();
            sndFireChannel = sndFire.play();
        }
        private function entFrame(event:Event):void
        {
            if (_root.gamePaused == false)
            {
                x += speed;
                if(this.x > (stage.width+ this.width))
                {
                    removeEventListener(Event.ENTER_FRAME, entFrame);
                    _root.projectilePlayerContainer.removeChild(this);
                }
            }
            if (_root.removeProjectiles == true)
            {
                removeEventListener(Event.ENTER_FRAME, entFrame);
                _root.projectilePlayerContainer.removeChild(this);
            }
        }
        public function removeListeners():void
        {
            removeEventListener(Event.ENTER_FRAME, entFrame);
        }
    }
}

When it has been declared in the main code as "". And besides, the "if (_root.gamePaused == false)" in the same exact class code works, even though it's essentially the same structure and the same kind of code is in another class and it works, but this doesn't. Why? What is going on here exactly?

I should also mention that the error appears in output log whenever "removeProjectiles = true" and in this case, it's at the end of the level when an upgrade menu shows up. Let me know if you would like to see that part of the code too.

How to check whether a child exists in class code?

Trying this the second time. Hopefully I won't get a lot of backlash this time.

I've attempted to make a weapon instance be spawned by player ship instance through the ship's Class code. My game has a lot of things tied into this and as expected, I didn't find anything so specific attempted anywhere. Essentially what my code does right now is spawn a weapon instance and has it move along with the ship because it's parented to it.

That's all great until I change ship type. Changing ship type changes a variable defined in the main game code (which you can also see called out in "if" statements in the code below) and changes the frames through which the game loops through. The ship has 6 frames, 2 for each ship type to make it look as if it has a dynamic animation and such.

Essentially, the weapon needs to have a different x and y coordinate relative to the ship when ship type is changed so that the weapon is visible where appropriate. Problem is though that I cannot change the weapon by turning the addWeapon function into an ENTER_FRAME function because otherwise it will just keep spawning multiple weapons every frame on top of each other. I could avoid this if I also made an "if" statement check for whether the weapon exists as a child of the player ship, but I have no idea how to do that; trying what others have done, with something along the lines of "if (!this.contains(weaponAttached))" gives me error #1119.

In short, I don't know how to check whether a child exists for the playerShip so that the game stops spawning more of them once one is created if I were to turn the addWeapon into an ENTER_FRAME function. I've also tried to make it so that the addWeapon simply calls out another ENTER_FRAME function, which would define the x and y coordinates of the weapon based on which type of ship is selected (remember that you can change ship type in-game before the first level and in-between levels), but the weaponAttached is a weapon instance variable which can only be used for that one addWeapon function and not outside of it, so this isn't a viable method.

Here is the Class code for playerShip:

package  {

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

    public class playerShipCode extends MovieClip {
        private var _root: Object;

        public function playerShipCode() {
            // constructor code
            addEventListener(Event.ADDED, beginClass);
            addEventListener(Event.ENTER_FRAME, entFrame);
            addWeapon();
        }
        private function beginClass(event:Event):void
        {
            _root = MovieClip(root);
        }
        private function addWeapon():void
        {
            var weaponAttached = new weaponCode();
            weaponAttached.scaleX = 1;
            weaponAttached.scaleY = 1;
            weaponAttached.x = this.x + 270;
            weaponAttached.y = this.y - 110;
            this.addChildAt(weaponAttached, 0);
        }
        private function entFrame(event:Event):void
        {
            if (_root.shipSelected == 1)
            {
                _root.playerXSpeed = 6;
                _root.playerYSpeed = 4;
                this.scaleX = .5;
                this.scaleY = .5;
                if (this.currentFrame == 3)
                {
                    this.gotoAndPlay(1);
                }
            }
            else if (_root.shipSelected == 2)
            {
                _root.playerXSpeed = 4;
                _root.playerYSpeed = 2;
                this.scaleX = .4;
                this.scaleY = .4;
                if (this.currentFrame == 1 || this.currentFrame == 2 || this.currentFrame == 5)
                {
                    this.gotoAndPlay(3);
                }
            }
            else if (_root.shipSelected == 3)
            {
                _root.playerXSpeed = 8;
                _root.playerYSpeed = 6;
                this.scaleX = .3;
                this.scaleY = .3;
                if (this.currentFrame == 1 || this.currentFrame == 2 || this.currentFrame == 3 || this.currentFrame == 4)
                {
                    this.gotoAndPlay(5);
                }
            }
        }
    }

}

actionscript 3 MouseEvent random color

i'm just getting started programming and wanted to know how to make the cards i made in actions script a random color with a MouseEvent. I have to do this for a a school project in Animate (adobe). (This is also the first time using this website). This is my code:

This is the card.as:

package  {

import flash.display.MovieClip;
import flash.geom.ColorTransform;
import flash.text.TextField;


public class card extends MovieClip {

    //praperties
    public var cardNumber:int;
    public var cardColor:ColorTransform;
    public var cardType:String;
    public var minNum:Number;
    public var maxNum:Number;
    public var textBox:TextField;

    //constructor
    public function card() {

        cardType = randomCardType();

        cardNumber = 5;
        cardColor = randomcardColor();
        trace(cardColor);
        trace(cardType);
        transform.colorTransform = cardColor;

        textBox = new TextField();
        addChild(textBox);
        textBox.text = String(cardType + "\n" + cardNumber);
        textBox.width = 100;
        textBox.height = 100;
        textBox.border = true;
    }

            //methods
    public function printinfo() :void {
        trace("cardNumber: '" + cardNumber + "'");
    }

    public function randomcardColor():ColorTransform {
        var kleur:ColorTransform = new ColorTransform();
        kleur.color = (Math.random() * 0xFFFFFF); 
        return kleur;
    }

    public function randomCardType(){
        var Name:Array = ["Knight","Archer","Wizard","Priest"];
        var randomNum:int = Math.floor(Math.random()* Name.length);
        return Name[randomNum];
    }

    function randomRange(minNum:Number, maxNum:Number):Number {
            return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
    }

    public function checkcardColor (otherColor) {
        if (cardColor == otherColor) {
            return true;
        }

        else {
            return false;
        }
    }
}   

}

and this is the cardgame.as:

package  {

import flash.display.MovieClip;
import fl.motion.Color;


public class cardgame extends MovieClip {

    //proparties
    public var cardA:card;
    public var cardB:card;
    public var cardC:card;
    public var cardD:card;

    // constructor code
    public function cardgame() {

        cardA = new card();
        cardA.x = 100;
        cardA.y = 100;
        cardA.width = 100;
        cardA.height = 100;
        this.addChild(cardA);

        cardB = new card();
        cardB.x = 450;
        cardB.y = 100;
        cardB.width = 100;
        cardB.height = 100;
        this.addChild(cardB);

        cardC = new card();
        cardC.x = 450;
        cardC.y = 300;
        cardC.width = 100;
        cardC.height = 100;
        this.addChild(cardC);

        cardD = new card();
        cardD.x = 100;
        cardD.y = 300;
        cardD.width = 100;
        cardD.height = 100;
        this.addChild(cardD);

        showMeTheWorld();                   
    }

    //methods
    public function showMeTheWorld() {
        cardA.printinfo();
        cardB.printinfo();
        cardC.printinfo();
        cardD.printinfo();
    }
}

}

AS3 - How to calculate intersection between drawing and bitmap

I'm trying to create a handwriting game with AS3 on Adobe Animate. I've created my board, functions(drawing, erasing, saving, printing and color pannel) so far. But i need to show a score. To do it i thought if i can calculate the percentege of intersection between drawing and a bitmap image(which is my background for now).

Is there any way to do it? Or can you at least tell me with which function should i try that? Thanks a lot.

Note: Here is 2 images from my game. You can easily understand what am i trying to explain and do.

players will try to draw correctly(drawn board)

Empty Board

vendredi 9 décembre 2016

Drag and drop game sort items to three targets

Please I need some help. I have spent 2 weeks trying to make a drag and drop game In cs4 actionscript 3.0 and am about to give up. I have gotten help so far, but the best suggestion I got was try and start from scratch instead of decompiling someone else's work. so here it is I have an array that looks like this

var answername:Array = new Array();
var answerdest:Array = new Array();
answername[0] = "gravel";
answerdest[0] = "1";
answername[1] = "Nuts and boltsl";
answerdest[1] = "1";
answername[2] = "water";
answerdest[2] = "2";
answername[3] = "gold";
answerdest[3] = "3";
answername[4] = "Iron";
answerdest[4] = "3";

I need three targets, and the ability to place the name of the item in my array (this is just a short piece of it) on the screen, if it is dropped on the target matching the answerdest number tor that item it is placed in a column, and the next item my array appears. If not it returns to its starting position. This seems like it should be easy to do but I am not a computer teacher I am a science teacher that is trying to make something for my student to use. I have basic coding skills for cs4.

This is as far as i have gotten but can not Figure out how to get the drag and drop part to check if it is in the correct spot. And get to to create a new drag-able if the answer is correct. I have created an answer target named "Answer1",

var objectoriginalX:Number;
var objectoriginalY:Number;
Atom.buttonMode = true;
Atom.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
Atom.addEventListener(MouseEvent.MOUSE_UP, dropObject);

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

        function pickupObject(event:MouseEvent):void {
        event.target.startDrag();

        event.target.parent.addChild(event.target);

        }

var dropCount:int = 0;
var dbCount:int=0;
var dbutton0;
    function dropObject (event:MouseEvent):void
{
    {
    event.target.stopDrag();

    var targetName = Answer1;
    trace (targetName);
    var matchingTarget:DisplayObject = getChildByName(targetName);
    if (event.target.dropTarget != null && event.target.dropTarget.parent == answerdest[1])

        {
            event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
            event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
            event.target.buttonMode = false;
            alpha = .8
            dropCount ++;
            event.target.x = 10
            event.target.y = (Number(dropCount) * 100);
            trace ("hit");




            trace (dropCount);
        } else 
        {
        event.target.x = 100;
        event.target.y = 111;
        trace ("miss");
        }

    } 
}


var answername:Array = new Array();
var answerdest:Array = new Array();
answername[0] = "gravel";
answerdest[0] = "1";
answername[1] = "Nuts and boltsl";
answerdest[1] = "Answer1";
answername[2] = "water";
answerdest[2] = "2";
answername[3] = "gold";
answerdest[3] = "3";
answername[4] = "Iron";
answerdest[4] = "3";
text3
text3.text = answername[1];

var myText:TextField = new TextField();
Atom.addChild(myText);
myText.text = answername[1] ;

Thanks for your help. I do not know if I am even on the correct track to do what I need it to do.

root actionscript 3.0 for flash

When i test my movie, there is a report problem like this "error #1006 clear is not function.

The script that I use is this

stage.addEventListener(MouseEvent.MOUSE_MOVE, Setting_awal);  
function Setting_awal(e:MouseEvent):void

{
    Xo = bola.x;
    Yo = bola.y;
    txt_Dx.text = "ΔX = "+(target.x-bola.x)/100+" m";
    txt_Dy.text = "ΔY = "+(bola.y-target.y)/100+" m";
    karet1.x = Xo-10;
    karet1.y = Yo;
    karet2.x = Xo+10;
    karet2.y = Yo;
    MovieClip(root).karet1.clear();
    MovieClip(root).karet1.lineStyle(15, 0x003300, 100);
    MovieClip(root).karet1.moveTo(0, 0);
    MovieClip(root).karet1.lineTo(-2, 0);
    MovieClip(root).karet2.clear();
    MovieClip(root).karet2.lineStyle(15, 0x005500, 100);
    MovieClip(root).karet2.moveTo(0, 0);
    MovieClip(root).karet2.lineTo(-15, 0);

    mc_var.x = 100000;

}

Can you show me the wrong point of mycode, please.

Can anybody help me?

what script in which i can save multiple user's name in same text file automaticlly?

i made flash quiz in flash cs6. i have following script in which i can save user name in .txt file but each time it ask to save file .

I used following script :

import flash.net.FileReference; import flash.events.MouseEvent;

var myfiles:FileReference=new FileReference(); saveButton.addEventListener(MouseEvent.CLICK,saveFunction);

function saveFunction(event:MouseEvent):void {

trace("ok");
myfiles.save(inputtxt.text,".txt");

}

jeudi 8 décembre 2016

Object does not return to original position when released cs4

I am making a drag and drop activity where multiple items are to be placed at the same target. I have action code on the main time line and then code attached to a sprite. 1) problem 1) When I release the object if it is correct it should snap to the top of that section. If it is incorrect it should return to its original orientation to be picked up again, Unfortunately it stays where I placed it, and does not move back to original place when it is incorrect. I have fixed other issues with this flash file as to if code is supposed to be on the main time line or in the sprite, but this does not seem to have an effect after the object is released. Near the end of the script there is _root.rlamp1.gotoAndPlay(1) this is a buzzer that goes off if the answer is incorrect. This is working correctly 2) problem 2) I do not know if these are related Items but if the correct placement is given I want the next item to start in the original position, but it is starting where my mouse is instead of the original position. I am relatively new to coding and am trying to make an activity for my science class to get instant feedback to see if they understand to concept. Thanks for your help.

  // [Action in Frame 1]

 answername = Array();
 answerdest = Array();
 answername[0] = "gravel";
 answerdest[0] = "1";
 answername[1] = "nuts and bolts";
 answerdest[1] = "1";
 answername[2] = "oxygen";
 answerdest[2] = "2";
 answername[3] = "helium";
 answerdest[3] = "2";
 answername[4] = "gold";
 answerdest[4] = "2";


        dbCount = 0;

        dbutton.duplicateMovieClip("dbutton" + dbCount,dbCount * 100);

        dbutton.visible = false;

        dbutton0.answer = answerdest[dbCount];

        dbutton0.theText.text = answername[dbCount];



    // This code is on the sprite and not on the main actionscript

   onClipEvent (load)
    {
        this.defx = _x;
        this.defy = _y;
        if (this.theText.text.length > 20)
        {
            this.theText._height = 31;
            this.theBox._height = 27;
        }
        else
        {

            this.theText._height = 19;
            this.theBox._height = 19;
        } // end else if
    }
    on (press)
    {
        if (this.noDrag !=true)
        {
            startDrag (this,false);
        }
    }


    on (release)
    {
        if (this.noDrag != true)
        {
            stopDrag ();
            if(this.hitTest(_root["dz" + this.answer]))
            {
                totalHeight = 0;
                for (v = 0; v < _root.dbCount; v++)
                {
                    if (_root["dbutton" + v].answer == this.answer)
                    {
                        totalHeight = totalHeight + _root["button" + v].theBox._height ;
                    } // end if
                } // end of for
                ++_root.dbCount;
                this .duplicateMovieClip("dbutton" + _root.dbCount, _root.dbCount * 100);
                _root["dbutton" + _root.dbCount]._x = this.defX;
                _root["dbutton" + _root.dbCount]._y = this.defY;
                _root["dbutton" + _root.dbCount].answer = _root.answerdest[_root.dbCount + 1];
                _root["dbutton" + _root.dbCount].theText.text = _root.answername[_root.dbCount +1];
                if (_root["dbutton" + _root.dbCount].theText.text == "undefined")
                {
                    _root["dbutton" + _root.dbCount].theText.text = "Finished!";
                    _root["dbutton" + _root.dbCount].noDrag = true;
                } // end if
                this.noDrag = true;
                this._y = _root["dz" + this.answer]._y + totalHeight;
                this._x = _root["dz" + this.answer]._x - _root["dz" + this.answer]._width / 2;
                ++_root["dz" + this.answer].numItems;
                _root.glamp1.gotoAndPlay (1);
                trace (dbcount);
            }
            else
            {
                this.X = this.defX;
                this._Y = this.defY;
                _root.rlamp1.gotoAndPlay(1);
            } // end if
        } // end else if
    }