How can i change a couple of MovieClip instance properties in mainTimeline by ActionScript 3 - actionscript-3

I'm a beginner at ActionScript 3. I want to change a MovieClip property. Also I want to give different names for every instance. So basically I want to reach all instances by one name.
A possible solution is writing code inside the MovieClip timeline with --this--.
But I want to do that in root area.
This a picture of my scene:
https://drive.google.com/file/d/0BzXd1GMzUo9HUWozdkJjYkxXSEk/view?usp=sharing
trace(ins1.alpha); // reaching with instance name without problem
trace(ins2.alpha); // reaching with other instance name without problem
/*
trace(MovieClip("mnsmb").alpha); // trying to reach with linkage name is not working
trace(MovieClip(mnsmb).alpha); // trying to reach with linkage name is not working
trace(MovieClip("menusembolu").alpha); // trying to reach with library symbol name is not working
trace(MovieClip(menusembolu).alpha); // trying to reach with library symbol name is not working
trace(mnsmb.alpha); // trying to reach with linkage name is not working
trace(menusembolu.alpha); // trying to reach with library symbol name is not working
*/

If you need to modify the alpha property of one instance (named inst1 in the Properties panel):
ins1.alpha = 0.1;
If you want modify the alpha of all the instances of your class, you can use the is operator (mnsmb is your AS Linkage):
var inst:DisplayObject;
for(var i:int = 0; i < numChildren; i++)
{
inst = this.getChildAt(i) as DisplayObject;
if (inst is mnsmb) inst.alpha = 0.1;
}
Note : In ActionScript 3.0 the instanceof operator should not be used to test for data type membership. See Adobe help about the is operator.

Related

Actionscript 3, access Symbol properties (AS Linkage)

I have created a new Symbol in the Flash IDE, I set it to Export for Actionscript and it has a class name of itemCoin
My stage has now 3 movieclips of that class, how can I:
count how many of itemCoin are on the stage
manipulate them, set and get their x, y individually etc. I tried itemCoin[0].x [1] [2]...etc but it throws an error
remove them from stage when needed
add an event listener that executes a function whenever a itemCoin is removed?
Instance name is used for referencing instances of objects.
For example, if you had a symbol of type ItemCoin (note that naming convention for a type usually starts with a capital letter):
When you place instances on the stage, you give them an instance name to reference them by (note that naming convention for an instance is usually camel case):
Now, properties may be accessed by referencing the instance name from code:
itemCoin1.x = 50;
itemCoin1.y = 25;
Remove it form stage:
removeChild(itemCoin1);
Add an event listener to the itemCoin1 instance for when it is removed:
import flash.events.Event;
itemCoin1.addEventListener(Event.REMOVED, removedHandler);
function removedHandler(event:Event):void {
trace("itemCoin1 was removed");
}
removeChild(itemCoin1);
Although generally a poor practice, you can iterate all children to identify instances. For example, to count the number of ItemCoins:
import flash.display.DisplayObject;
var count:uint = 0;
for (var i:uint = 0; i < numChildren; i++) {
var obj:DisplayObject = getChildAt(i);
if (obj is ItemCoin) {
trace("Found " + ++count + " item coins so far.");
}
}
To comprehensively search the display list, you'd have to traverse children of all display objects.
If knowing the total number of instances on the stage was that important, it might be a better idea to define some ActionScript inside the component or within a Factory class to reference count when added to stage and removed from stage.

How can I give flash stage instances unique properties in Flash Professional to pass to AS3 script?

I've started building a rough game engine framework in Flash Professional and I'm curious how I can create objects in the Flash library that I'm able to drag onto the stage and assign properties that are accessible from AS3.
Example:
I want to create a switch object (e.g. a light switch), so that when the player interactes with it, it triggers something specific in code such as a light in the room turns on.
I understand that Flash has built in UI components that you can define properties within the Flash Professional environment (see image below), and I'm wondering if there's a way to create my own custom style components so that I can essentially have my level file open in flash (.fla) and then drag a switch component from my library, and type in some information such as what light it is controlling, and any other information I want.
(above is an example of the type of parameter control I'm looking for)
I've read a bit about extending the flash UIComponent class but I feel that that's not the right approach because it's overkill for what I want. All I want is to pass some basic parameters from a library stage instance into AS3. I do not want to pass data via the instance name because this seems very messy if I want to have more complex interaction.
Thanks!
I would create a "switch" movie clip and export it to actionscrip, same with a "light" movie clip. The in the main class .as file I would inset them into the stage, using addChild (clips) and then add a click listener to the "switch" movie clip to control the "light".
This can be easily done.
Component(s) are wrong approach in my opinion.
Firstly you would want to setup Actionscript linkage / label your Library item.
In Library Panel.
- Right Click on "yourMC" >> click "Properties".
- In Properties dialog Tick "Export for Action Script"
- Then Name your Class eg "yourMC_Class"
now MC is ready to be referenced in your code.
next you would want to Dynamically add your "yourMC" from library to stage.
which can be done like such.
// first reference library item
var yourMC_ref:yourMC_Class = new yourMC_Class();
// Then load dynamic mc item into var
var your_MC_OBJ = yourMC_ref;
// then add your MC to stage.
this.addChild(your_MC_OBJ);
your_MC_OBJ.x = 200;
your_MC_OBJ.y = 100;
in a nutshell that's how I add library items to stage.
Obviously thats the basic function / code.
In a project I would have all code in an external class, in which case you would just set vars as public vars
public var yourMC_ref:yourMC_Class = new yourMC_Class();
public var your_MC_OBJ = yourMC_ref;
and the last 3 lines of code into a public function
public function ADD_First_MC()
{
this.addChild(your_MC_OBJ);
your_MC_OBJ.x = 200;
your_MC_OBJ.y = 100;
}
Now 'your_MC_OBJ' can be used in more complex ways.
eg. to create a light switch there are many options depending on how you need to approch functionality.
eg. Apply a different MC library item to "your_MC_OBJ"
play specific frame within MCs.
However If it was me I would just use mouse function to switch light on or off using addChild removeChild.
eg.
public var LightON = 0;
public var yourMC_ref:yourMC_Class = new yourMC_Class();
public var your_MC_OBJ = yourMC_ref;
then create a public function that handles on / off events
public function LightON_OFF()
{
if(LightON == 1)
{
this.addChild(your_MC_OBJ);
your_MC_OBJ.x = 200;
your_MC_OBJ.y = 100;
}
if(LightON == 0)
{
this.removeChild(your_MC_OBJ);
}
}
Hope this helps.
So, for what you want, while it may not be the best way to do what you want, I understand it's your experience you are constructing.
Use components, yes...in the following way (the most simple one):
Create a Movie Clip
Right-click it in library
Click on "Component Definitions"
Add a property, set a name, a variable name (var test, for this matter) and a default value
Click OK
Open your movie clip
Open code for the first frame and declare the variable without an initial value (var test:String;)
Trace it's value ( trace( test ); )
Go back to the stage root
Drag and drop the item from library to stage
Test it (Cmd/Ctrl + Enter) (maybe it will print null, dunno why, it ignores the default value sometimes)
Select your component on stage
Open the properties panel (Windows > Properties)
Go to Component Parameters on this panel and change the property value
You should see the value traced on console
And, I think, like this you can use properties from components for what you want, like using a String and getting the controlled mc by its name.
Good luck
I think what people are trying to say is that you can have the whole thing is data driven, and so you can combine the IDE with the data to come up with your final game.
But consider this ... it might be what you want.
If you have, for instance, a BaseSwitch Class:
public Class BaseSwitch extends MovieClip {
private var _lightName:String;
private var _light:Light;
public function get lightName():String {
return lightName;
}
public function set lightName(value:String):void {
if (value != _lightName) {
_lightnName = value;
//Note I don't advocate having children reach into their parents like this,
//but you sound like you don't want the parent involved in the process, so
//this is one way you could do it.
if (parent.hasOwnProperty(lightName) && parent[lightName] is Light) {
_light = parent[lightName];
} else {
trace('Could not find light', _lightName);
}
}
}
//other code to listen for gestures and operate the light
}
Now, when you want a switch to operate a specific light name, create a library instance and set its base class to BaseSwitch. When you close the dialog where you set the base Class, you'll notice that it gives you a dialogue that it couldn't find the Class in the Class path and one will be generated. You're going to replace it with a Class that sets the lightName. Create a new AS3 Class in the root directory with the same name as your library instance. It should look something like this:
public class SpecificSwitch {
public function SpecificSwitch() {
super();
lightName = 'theSwitch';
}
}
Other possible choices involve having the parent Class match up instances of switch with instances of light based on name, so if it finds a light1 and a light1Switch, it either gives a reference to the light to the switch or it simply sets up a mapping in its own event listening system.

AS3 Multiple instance names in one MC

I apologize for how confusing this question is.
I have a Movie Clip that is a car. In the car movie clip there are four different angles to the car. (e.g. left, right, front back). I dynamically change the body color of the car. In each angle of the car, the body of the car has an instance name "body." I change the color with the code :
var tempcar = "car_mc" + i;
var myNewTransform = new ColorTransform();
myNewTransform.color = 0x000000 //in real life this is a random value
this[tempcar].body.transform.colorTransform = myNewTransform;
Everything works fine, until I tell the car movie clip to gotoAndPlay the frame "front," where we see the front side of the car, and I try and apply the color change again to the body of the front of the car. I get the error :
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Is there a better way to do what I am trying to do?
That's the old ActionScript 2 way of handling things. In ActionScript the container is not always a MovieClip, which would except the hash to access a dynamic field. Also, if you'd added it to the display list via addChild, the result would be different as well, since it is not the case in ActionScript 3, that could address the child automatically.
You should use an Array to store and access dynamically created instances.
// clazz would be the symbol
function createInstance(container:DisplayObjectContainer, clazz:Class, list:Array):Sprite
{
const child:MovieClip = new clazz() as MovieClip;
if (!child) throw new ArgumentError("Wrong type given");
return list[list.length] = container.addChild(child);
}
function getInstanceAt(index:int, list:Array):Sprite
{
return list[index] as Sprite;
}

I can't seem to access automatically named objects (instance##) placed on the stage in AS3, am I missing something?

I have a movieclip in the library that is added to the stage dynamically in the document class's actionscript. This movieclip contains many many child images that were imported directly from photoshop at their original positions (which must be preserved).
I do not want to manually name every single image instance, as there are dozens upon dozens.
I have already gone through and manually converted the images to symbols, as apparently flash won't recognize the "bitmap" objects as children of a parent movieclip in AS3 (numChildren doesn't see the bitmaps, but it sees the symbols).
I have an array filled with references to the dozens of children, and I loop through it, checking if each one is under the mouse when clicked. However, somehow, it is not detecting when I click over the items unless I manually name the child symbols (I tested by manually naming a few of them -- those ones became click-sensitive.)
I have already done trace() debugging all throughout the code, verifying that my array is full of data, that the data is, in fact, the names of the instances (automatically named, IE instance45, instance46, instance47, etc.), verifying that the function is running on click, verifying that the code works properly if I manually name the symbols.
Can any one see what's going wrong, or what aspect of flash I am failing to understand?
Here is the code:
//check each animal to see if it was clicked on
private function check_animal_hits():void
{
var i:int = 0;
var animal:Object = this.animal_container;
for (i=0; i<animal.mussels.length; i++)
{
if (this.instance_under_cursor(animal.mussels[i].name))
{
var animal_data = new Object();
animal_data.animal = "mussel";
this.send_data(animal_data);
}
}
}
Here is the code for the instance_under_cursor() method:
// Used for finding out if a certain instance is underneath the cursor the instance name is a string
private function instance_under_cursor(instance_name)
{
var i:Number;
var pt:Point = new Point(mouseX,mouseY);
var objects:Array = stage.getObjectsUnderPoint(pt);
var buttons:Array = new Array ;
var o:DisplayObject;
var myMovieClip:MovieClip;
// add items under mouseclick to an array
for (i = 0; i < objects.length; i++)
{
o = objects[i];
while (! o.parent is MovieClip)
{
o = o.parent;
}
myMovieClip = o.parent as MovieClip;
buttons.push(myMovieClip.name);
}
if (buttons.indexOf(instance_name) >= 0)
{
return true;
}
return false;
}
Update:
I believe I have narrowed it down to a problem with getObjectsUnderPoint() not detecting the objects unless they are named manually.
That is the most bizarre way to find objects under mouse pointer... There is a built-in function that does exactly that. But, that aside, you shouldn't probably rely on instance names as they are irrelevant / can be changed / kept solely for historical reasons. The code that makes use of this property is a subject to refactoring.
However, what you have observed might be this: when you put images on the scene in Flash CS, Flash will try to optimize it by reducing them all to a shape with a bitmap fill. Once you convert them to symbols, it won't be able to do it (as it assumes you want to use them later), but it will create Bitmpas instead - Bitmap is not an interactive object - i.e. it doesn't register mouse events - no point in adding it into what's returned from getObjectsUnderPoint(). Obviously, what you want to do, is to make them something interactive - like Sprite for example. Thus, your testing for parent being a MovieClip misses the point - as the parent needs not be MovieClip (could be Sprite or SimpleButton or Loader).
But, if you could explain what did you need the instance_under_cursor function for, there may be a better way to do what it was meant to do.

How to add all symbols in library folder to stage at runtime

I just submitted this question but i can't see if it posted anywhere, so I apologize if this is a duplicate.
For a Flash CS4 project, I am constantly importing new images, converting them to movieclips and storing them in the library under an "Ornaments" folder. All of these ornaments need to be on the stage in a certain place when the program is initialized. Instead of having to drag the new symbols onto the stage every time I add a new, is it possible to add all of the symbols in the "Ornament" library folder to the stage at runtime?
Thanks
You can do it in code if you wish, but you'd have to still add the names of the symbols to the code. That is, the folder is merely a convenience for organizing within the CS4 library and it does not translate to code (AFAIK).
To instantiate the item in AS3, simply right click the symbol in the library and check the box labelled "Export for ActionScript". If you can't see it, click the Advanced button. It will default the Class to the name of the symbol. That will be the class you can instantiate in ActionScript to put an instance on stage.
You could keep an array of the ornament names and loop through them adding them to the stage:
var ornaments:Array = [OrnamentGold, OrnamentSilver, OrnamentBronze];
for each(var ornament:Class in ornaments)
{
var ornamentClip:MovieClip = new ornament();
addChild(ornamentClip);
}
If you name all of your instances the same with only a trailing digit incremented, you can save yourself some time and just increment a single number:
const NUM_ORNAMENTS:int = 5;
for(var i:int = 0; i < NUM_ORNAMENTS; i++)
{
// ornaments are names Ornament0, Ornament1, Ornament2, etc. in the library
var ornamentClass:Class = new getDefinitionByName("Ornament" + i) as Class;
var ornamentClip:MovieClip = new ornamentClass();
addChild(ornamentClip);
}