Having problems with hitTestObject-ing a child - actionscript-3

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(...).

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().

AS3 Return Object currently under another Object without HitTestObject

Is it possible to return the Object that is underneath/in contact with another Object without using hitTestObject ?
I'm wondering if I can remove the need to loop through an array of 'active' Objects and simply get the instance that's underneath at any given time. Possibly using as3 events ?
many thanks SC
You can use the getObjectsUnderPoint() method of the DisplayObjectContainer class.
Be carefully, using a getObjectsUnderPoint().
getObjectsUnderPoint() return types Array. this mean specify Point above all DisplayObjects return. sometimes you do not want to get the value. So the objects in the array must be verified. Faced this problem, especially DisplayObjects when they overlap or if you load the other swf

Access of (as of yet) undefined Property AS3

I have a function that creates a pointer on the screen after certain other conditions are met. I have a separate function that I use for moving the pointer around the screen (since the conditions for the first function and the second function are mutually exclusive). The problem, as far as I can tell, is that upon loading the movie flash instantly looks at all the code on the main timeline and realizes that my second function, the one for moving the pointer, is referencing the pointer's .x and .y even though the pointer doesn't exist. The second function's conditions prevent it from occurring until the first function has executed and the pointer has been created.
My question is, is there any command that I can use to tell flash "pointer.x and pointer.y don't exist YET, but by the time you need them they will, so chill" or do I need to start burying code on the movieclip itself or something? I'm still very new to AS3 so my methods aren't the most... Effective yet.
Yes, there is some. You go into second function and check:
if (!pointer) return;
This will check if "pointer" exists, and is not null or undefined. Basically this is the correct method of programming, first check availability of your objects, then access them.

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

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

TypeError: Error #1009 Actionscript 3

I am extremely frustrated. I'm following a tutorial and mimicing it on my own. I have been able to sort out most of the errors so far but this one has me stumped. I have tried replacing all of the class files with the tutorial specimen ones but i still get the error.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.senocular.utils::KeyObject/construct()
at com.senocular.utils::KeyObject()
at com.asgamer.basics1::Ship()
at com.asgamer.basics1::Engine()
Now, not really understanding the error properly I paste dumped the files online for you to look at.
Ship class: textbin.com/78z35
Engine class: textbin.com/32b24
KeyObject class: textbin.com/p2725
As the error still occured when using the specimen class files I really have no idea where to begin. I will gladly try out any suggestions.
Tip: If you allow debugging, the exception will tell you the exact line in the source code where the Error is being thrown. Assuming you're using the Flash IDE, go to publish settings and in the Flash tab check "Permit debugging". This will makes thing much easier for you.
Anyway, you have an error message. If you read it carefully, you can narrow down where the problem is. I don't know if you are a programmer or you have any interest in being one; if you're not, this answer will hopefully solve this particular problem. Anyway, if you don't mind the rambling, let me tell you that if you're interested in becoming a better programmer, paying attention to errors and learning how to debug / troubleshoot problems is one of the most important abilities you need to develop (if not the most important one); so maybe this will give you a few hints you can use to solve other problems as well.
The message says:
Cannot access a property or method of
a null object reference.
This means, at some point, you did something like this:
someobject.someMethod();
or
someobject.someProperty = "foo";
And someobject happened to be null. You can't call methods or access properties of null.
Ok, so now you know, somewhere, a variable had null as its value. Notice that the fact that you define a variable of property doesn't mean it actually holds an object.
This just says that a variable called mySprite can hold an object of the type Sprite:
var mySprite:Sprite;
But until at some point you create a Sprite and assign it to mySprite, the value held by mySprite will be null. If you do:
mySprite.x = 0;
Before initializing mySprite (i.e. before assigning a Sprite to it), you will have this same Null Reference error.
This error message also offers some helpul context, which you can use to your advantage (in them old days... errors in Flash were silent; when things didn't work, you had to manually trace down the problem).
Ok, let's break this error message down:
at com.senocular.utils::KeyObject/construct()
at com.senocular.utils::KeyObject()
at com.asgamer.basics1::Ship()
at com.asgamer.basics1::Engine()
What you have above is called a stack trace. It basically tells you where the code blew up, and also gives you some context: how did you get there.
The first line tells where the error actually occurred. That is, the construct method in the KeyObject object. That method was called from the KeyObject constructor, which was in turn called from the Ship constructor, which was in turn called from the Engine constructor.
Now, let's analyze how you got there, following the stack trace, bottom-up:
Code in Engine constructor:
ourShip = new Ship(stage);
This creates a new Ship object. It passes a reference to the stage to the Ship constructor method.
Code in Ship constructor:
this.stageRef = stageRef;
key = new KeyObject(stageRef);
It grabs the ref passed in the previous step. It stores it and creates a new KeyObject object. The KeyObject constructor is passed a reference to the stage (which is the same ref that was passed from Engine to Ship).
Code in KeyObject constructor:
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
Now we got to the point where the error message told you the problem was. So, somewhere, you are using a variable that holds null and trying to access one of its methods or properties.
This KeyObject stores the reference to stage it was passed in a static variable and creates a new Object object. So far, no problems. KeyObject cannot be null (it's a reference to a Class). The second line itself cannot have this null problem either. So, if this is all the code in that method, the problem has to be either in the third or the fourth line. Both access the stage reference you passed and try to call a method (addEventListener) on it. So if one fails, the other will fail as well. Then, the third line: that's where the problem has to be.
So, at that point stage is null. As said previously, you can't call a method on null, and that's what the error is telling you.
Now, if you get back to the first method call, you can see this is the origin of the problem:
ourShip = new Ship(stage);
You can be pretty sure that, at this point, stage was null. Add that to the fact that Engine extends MovieClip (which is in turn a DisplayObject), and to the fact that any DisplayObject has a reference to the stage object only while it's added to the display list. The conclusion: an instance of Engine was not attached to the display list when its constructor was ran.
A way to fix this (there might be others) could be moving the code in the Engine constructor to a separate function that will be executed only if / when the Engine object has a valid reference to the stage object.
public function Engine() : void {
if(stage) {
initialize();
} else {
addEventListener(Event.ADDED_TO_STAGE,initialize);
}
}
private function initialize(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE,initialize);
// here goes the code that's currently in Engine constructor
}
Hope this helps.
I have a feeling your stage property is null.
You have have to test this yourself with a trace of the stage object.
In the first line in the constructor of you Engine class, add:
trace(stage);
Add that just above this line:
ourShip = new Ship(stage);
If it traces "null" then that is your problem.