this[String] can't be added into a MovieClip - actionscript-3

Lets say I have a MovieClip called "Box", and "String" is actually 'box' just that its not a MovieClip
The problem I'm facing now is I can't use something like circle.addChild(this[String])
I've tried tracing this[Strin]==Box and the result returns true.
And when I remove circle.addChild(this[String]), it does not add the Box into it.
BUT, when I traced is there any new object added to circle, the amount still remains the same.
Any idea what seems to be the problem here?

If I understood you, you are trying to add a MovieClip called (has a instance name of) String inside another MovieClip called Box, right?
Well, you can't give the name String to an object, because String is a class name in ActionScript 3.0
You can't name any object with any class name or protected keyword, such if, for, class, Boolean...
Those are words that ActionsScript uses globally (they are Top Level keywords).
Also, note that although you can name an object (give it an instance name of) MovieClip, Sprite, Loader, Stage and such, all theses names are used by ActionScript as class names, inside packages, that can be imported into your animation/application, and Flash will automatically import almost every one of them for you.
If you name your objects with those words you run some risks, like codes that don't work properly or don't compile at all...
As pointed by #Bosworth99 and #merv, you may note, as well, the naming conventions used by ActionScript, the UpperCamelCase and lowerCamelCase.
Classes are (by convention) written with UpperCamelCase (with the first letter capitalized), which indicates that name is a class name.
Objects are, generally, written with lowerCamelCase (with lower first letter and every new composed word with upper case), indicating that word is a object name (or another keyword, which may be reserved already).

Your syntax is a little odd - you say you have a MC called 'Box'. Are you creating this in the flash ide - or programatically? either way - you appear to be referencing Classes, and not instances of a class (an object). Try:
var _circle:MovieClip;
var _box:Sprite;
private function createDisplayObjects():void
{
_circle = new MovieClip();
this.addChild(_circle);
_box = new Sprite();
_circle.addChild(_box);
}
And - just as a generally agreed upon practice, class names are capitalized, and instance name are lowerCamelCase. I like underscores prefixing private vars, as well.
NemoStein is absolutely correct - reserved keywords will bork your code everytime...
good luck

Related

method .attachMovie() is no longer supported .Flash to AS3 conversion

I am completing an online tutorial and manipulating it suit my website. I've come across this code...
`// Create a menu item movie clip in the menu_mc instance on the main timeline
// for each item element offsetting each additional further down the screen
var item_mc = menu_mc.attachMovie("movieitem","item"+item_count, item_count);
item_mc._x = item_count * item_spacing;
item_count++;`
The following line gives me a problem (the method is no longer supported)
var item_mc = menu_mc.attachMovie("movieitem","item"+item_count, item_count);
How can i achieve this?
I've tried the following with no joy. message too many arguments?
var mItem:movieitem = new movieitem;
var item_mc = menu_mc.addChild(mItem,mItem+item_count, item_count);
addChild() only accepts 1 argument, which is the display object itself. Also, it looks like you're missing brackets when you create your object and by convention, class names are capitalised.
var mItem:movieitem = new movieitem();
Edit based on my comment
Looking at the documentation for attachMovie() for AS2 (wow, been awhile since I've looked at this), it takes in 3 arguments:
id:String, name:String, depth:Number
Now the id is used to grab a movieclip from the library. This is no longer needed as you've already created a movieclip object from your library in the line before:
var mItem:Movieitem = new Movieitem();
The second argument name is used to create a unique instance name for the created moviclip from the library. You don't really need this. In the line where you create the movieclip (see above), you already have a unique reference you can use to access the movieclip. Interestingly, attachMovie() also returns a reference -I've never ever found a use for the instance names given with the 'name' argument. I just use the reference returned to access it, which you are already doing.
The third argument depth determines which depth the movieclip is placed at. In your case, I am guessing that ' item_count' is just a number that increases, which effectively puts that movie clip at the highest depth when that line is executed. By default, addChild() will automatically do this for you and put the display object (your movieclip) at the highest depth within the parent at the time it is added. So, unless you wanted it at a specific depth/overlapping order, you don't really need to pass this in either. If you did want to add something at a specific depth, look at addChildAt()
Hence as mentioned before, you can just pass in the reference to your movieclip/display object in to addChild().

Having problems with hitTestObject-ing a child

I've just started to learn actionscript for a month or so, and I've been stuck on this part of the code for about 2 days now ><
So basically, I wanted to write a hitTestObject in a movieclip ("fire_mc") to detect if it overlaps the the child I added on stage (enemy)
So here's what I wrote in the main stage...
var newtarget:enemy=new enemy();
stage.addChild(newtarget);
newtarget.x=40;
newtarget.y=30;
and every time I traced the newtarget in the fire_mc, it turns out to be NULL...
So should I be tracing enemy or newtarget? (Cuz I tried both and nothing works).
And how can I hitTestObject in the fire_mc movieclip?
Is it possible for me to hitTestObject newtarget if I were to create multiple newtarget-s?
If not, what should I do?
And can someone tell me the difference between root, and MovieClip(root) (Because sometimes in a movieclip I have to use the former one to work, and sometimes the latter, and I have no idea why cuz I'm all referencing to the same place)
Sorry for these simple and lengthy questions, I'm really just a noob and I tried looking up for answers in the web for hours, but nothing helpful turned up><
Thanks in advance :)
In this statement
var newtarget:enemy=new enemy();
var - keyword used to define varibles, newtarget - variable name in which pointer to new class instance stored, :enemy - data type (the class name), new - keyword used to create new class instances, and finally enemy is class constructor (by the way there is a rule of good manners by which class names are capitalized)
So answer for you question which should you use when you want check is some is overlapping is 'newtarget'.
Now about hit test - all you need do to check if two objects hit each other is correctly use their references from the part of project where your code is writen.
For example if you have your fire_mc on MainTimeline created by IDE, and code of creation of you enemy instance stored in newtarget sameplace, then if you check will be placed in frame of MainTimeline where both object present it will be like this
fire_mc.hitTestObject(newtarget);
or this
newtarget.hitTestObject(fire_mc);
All these statements give you same result - if objects intersect each other you have true returned.
If you created 'newtarget' on MainTimeline and checks will be from fire_mc (which is on MainTimeline to) frame, then code will something like that
this.hitTestObject(MovieClip(root).newtarget);
Now about root. Primarily it is a property of DisplayObject in which reference to the top-most display object in swf-file structure is stored. So as such it is inherited by all child classes. So here's the trick. When you try get your objects in swf structure using root here the differences are based on the fact that root always return object as DisplayObject and that means what if you object contains something that DisplayObject shouldn't you can't get it. So you must convert returned reference to need data-type usign MovieClip(...).

Error #2136: swf contains invalid data

public function starttank(event:MouseEvent):void
{
var Tankdrive:TankDrive = new TankDrive();
Tankdrive.tankstart();
}
It's saying that something in that function contains invalid data.
I have no idea what it is, i checked TankDrive and tankstart(); and both are correct, tankstart() is a public function...
I'm stumped...
EDIT: Error:
Error #2136: The SWF file file:///C|/Users/BigRed/Desktop/TankDrive/TankDrive.swf contains invalid data.
at mainmenu/starttank()
That's the error...
And above the starttank() function is still the same...
Ok, I looked over the files.
I'm puzzled by what you are trying to do.
Your Document class is TankDrive, and it creates an instance of mainmenu, which create ANOTHER instance of TankDrive when you click a button. Which is not what I think you want to do, or you think it's allowing you to access your document class. -- it's not. It's attempting to create a whole new instance of your game.
In short, your design is not making sense, and it's also causing a conflict with the document class resulting in that error.
The quick solution is to NOT have your EventListener & handler for the click in the mainmenu class, and then call the tankstart() method of your document class instead of attempting to create a new instance of TankDrive.
First move that listener into the document class and modify like this :
main.enterTank.addEventListener(MouseEvent.CLICK, starttank);
and then move your handler to the TankDrive class and modify as follows :
public function starttank(event:MouseEvent):void
{
tankstart();
}
This is not the only way to do this, and not really the way that I would do it. But I think that discussion is beyond the scope of this question.
If you want you can contact me at prototype.in.training#gmail.com for more details on that.
The problem is that you have an instance name that's also a class name (and the compiler has assumed that you meant to reference the latter). You probably meant to call your TankDrive variable 'tankDrive', so changing your code snippet to the following will probably help:
public function starttank(event:MouseEvent):void
{
var tankdrive:TankDrive = new TankDrive();
tankdrive.tankstart();
}
It's common and recommended to start all public variable names with a lower case letter, private variables with an underscore, and class names with a capital, though this isn't enforced by the language itself, so this kind of thing can happen.
Here are some guides on conventional variable and function naming that can help you keep track of what each of your vars and functions are supposed to do:
http://www.adobe.com/devnet/actionscript/learning/as3-fundamentals/variables.html
http://www.adobe.com/devnet/actionscript/learning/as3-fundamentals/functions.html
Good luck!

Access of undefined property data flex

I'm learning flex/flash and I'm lost on this one. I have used the "data" in a bunch of views and it works fine. For some reason it isn't working here.
I set a field to a string here:
function LoginLoaded (e:Event):void {
trace(e.target.data);
var ServerReturn:String;
ServerReturn = new String(e.target.data);
data.UserCommonReturnData = ServerReturn;
navigator.pushView(CommonPlaces, data);
}
and here in the common places view I try to load it back:
var CommonPlacesData:String = new String();
var CurrentSelect:String = new String();
CommonPlacesData = new String(data.UserCommonReturnData);
This gives the error "Access of undefined property data" I don't get it because calling on something like data.PickUpTime (also a string) works fine in other views.
The data begins in the first view like this:
[Bindable] public var User:ObjectProxy = new ObjectProxy();
User.ID = "2314084";
navigator.pushView(TaxiNowOrLaterView, User);
then in later views I call on it like this: (works fine)
var PickUpString:String = new String(data.ID);
Any help would be great!! Thanks!!!
There are few things about your code. First, you really should make it a habit to name the identifiers as appropriate to the language. Identifiers that start with the capital letter and subsequently use minuscule letters for the rest of the logical part of the word (system alternatively known as PascalCase) is employed to only name classes. The rest of identifiers should use camelCase (similar to PascalCase, but the first letter isn't capitalized)**. This greatly reduces the effort at understanding your code. A seasoned AS3 programmer would interpret your code as follows:
// Static constant (!) ID of the class User is assigned (?) a value of "2314084"
User.ID = "2314084";
// invoke a method pushView of a local variable navigator with arguments
// of which first is the class TaxiNowOrLater, the second is the class User
navigator.pushView(TaxiNowOrLaterView, User);
while, perhaps, you didn't mean it.
new String();
In the context of AS3 makes no sense at all. Strings are never references, are immutable and have literal syntax the majority of programmers agreed upon. The code above is identical to "". In the similar way, new String(anotherString) has exact same effect as anotherString.
Your question: event.target may be many different things, some of them may have property called "data" and some may not. The general approach to this problem is that you need to cast the value of event.currentTarget or event.target to the type you expect to dispatch the event. Suppose you are expecting an event from an instance of a Button class, then:
private function clickHandler(event:MouseEvent):void {
if (Button(event.currentTarget).enabled) // do things
}
This will not protect you from an error, if the same event was dispatched by an object, which is not a button, but will make the error reporting more conscious, because it would tell you what class was it trying to cast to what other class, when it failed.
If your program logic requires that the handler be aware of events it shouldn't handle (why?) you could then write it like this:
private function clickHandler(event:MouseEvent):void {
var button:Button = event.currentTarget as Button;
if (button && button.enabled) // do things
}
event.target vs event.currentTarget - very-very rarely you would need the event.target, most of the time you need the currentTarget. I'm not saying it is wrong, but, it looks like it might be the problem. target is the object that was the first cause of the event. Events may bubble, which means they may travel the display list hierarchy up and down, first from the parent to child, then in reverse direction. In the example below, suppose there was a label on the button, which was clicked once the event was generated - in such case, even if you added a listener to the button, event.target would be the button label, not the button. currentTarget is, on the contrary, the immediate object which dispatched the event into the handler.
Few more things: ObjectProxy is an idiotic class, you probably shouldn't use at any event. It serves no purpose and, perhaps, buggy, but very few cared to discover its bugs so far. In a nutshell, what it does is as follows: it creates an object, which "watches" dynamic creation, assignment and removal of its properties and dispatches events when these events happen. This behavior is prone to a lot of errors and implicit bugs. For example, is foo.bar = "baz"; foo.bar = "baz"; a reassignment of the same property or not? Is foo.bar.baz = "fizzbuzz"; a modification of foo.bar? What if property name is not a sting? And so on.
Why you shouldn't use it: there is always a better way to treat your data. A more transparent, easier to debug, more efficient. This class is a prototype, which had never really worked. Besides having the behavior described above, it is huge in terms of lines of code that were used to write it. Debugging the errors that happen inside of it requires a lot of time and patience, which are certainly not worth it.
If you need an object to represent a user, define a class, with properties you expect the user to have and just use that class - this will make debugging and understanding your code much easier.
[Bindable] metadata is evil. I can't tell you you should avoid it, because it is used too often, but, I will. You should avoid it as much as possible. I didn't yet encounter an instance of when the use of this meta would be justified. Much in the similar spirit as ObjectProxy it is a prototype, something designed for lazy programmers w/o much consideration for either performance or corner cases. This is, again, a source of a lot of implicit bugs, typically difficult to spot due to the code generated around this meta "swallowing" the errors. The alternative to this meta is plain addEventListener(...) code with custom events.
Unfortunately, a lot of tutorial will use this kind of code to have you quickly started with the language + framework...
** there are some exceptions to this rule: constants are all upper-case and namespace names use underscores to separate the logical part of the word, but never use uppercase letters.

Is it bad to prefix all of my framework class names?

I develop a lot of frameworks for Flash games and applications. I have always prefixed my class names with a random character or two, to avoid conflict with class names that the developer may already have, for example:
class LEntity
Recently I had a co-worker blast me for poor and "annoying" naming of classes who then proceeded to rename every class in the frameworks I've created for people here to use.
I'm having trouble explaining my reasoning thoroughly enough for him to accept what I've done as a good approach.
Is what I've done above actually a bad thing? If not, how can I explain otherwise? If so, why?
Comments are asking about namespaces - I know AS3 in this example has what I know to be called a namespace but I'm not sure if this is the same thing or if it can be used as expected.
Given that Actionscript supports namespaces, there is no reason to use prefixes simply to prevent naming clashes. That's what namespaces are for.
Some people like to use namespaces to significy member variables (ie, underscore prefix, or sometimes m_) and that has some merit, but simply for the sake of name clashing no.
It sounds like you don't quite understand what namespacespackages are in AS3.
An example:
//Class1.as
package com.test.someModule { //This is the package/namespace
public class Class1 {...}
}
//Class2.as
package com.test.otherModule {
import com.test.someModule.Class1; //Class1 can be used as "Class1" now. Otherwise you would do "com.test.someModule.Class1"
import com.test.someModule.*; //You can also use the "*" to "import" all classes in that package
}
I have to agree with your co-worker, your class names are 'annoying'.
In Actionscript 3 we use the package name to define the namespace of a class. If you're not sure what namespace means, take the wikipedia definition (as of the time of writing):
"In general, a namespace is a container for a set of identifiers
(names), and allows the disambiguation of homonym identifiers residing
in different namespaces."
So you will never "conflict with class names" as long as you name your packages correctly. Most developers use what is called the reverse domain notation to name their packages (e.g com.mywebsite.MyGenericNamedClass). Domain names are unique so it's very unlikely you would clash with another class.
As a rule of thumb the class name should be as descriptive as possible, so some of your class names will be the same as someone else's class. Take the default Sprite class for instance:
import flash.display.Sprite;
import uk.co.mywebsite.Sprite;
if you then initialize an object:
var mySprite:Sprite = new Sprite();
The compiler would not know which Sprite you want to initialize (is it the flash sprite or your own custom sprite), and it would throw an error.
The solution is simple: because your packages have been named properly, all you need to do is to use the full class name including the package name to initialize your object:
var mySprite:uk.co.mywebsite.Sprite = new uk.co.mywebsite.Sprite();
var myOtherSprite:flash.display.Sprite = new flash.display.Sprite();
Mind you, you would rarely need to do that. This is only necessary if you want to use those two classes (the default Sprite and your own Sprite) in the same scope. Generally, you would only import your own class:
/* we are not importing this any more
import flash.display.Sprite;*/
//only importing my own class
import uk.co.mywebsite.Sprite;
/* now I can initialize my object without using the full class name, and the compiler knows
I mean my own Sprite class */
var mySprite:Sprite = new Sprite();