Is there a way to know which object an object is colliding with?... I want to create a 'box object' in flash that can identify any other object(Movieclips) that collides with it. For example, if I drop the box on the 'field' (engine or world), and i put anything inside it, I would like the box to tell me what kind of object it is colliding with. I can't use hitTestObject because I don't know which object the box will collide with in advance.
A rough pesudocode to what I want to achieve is as follows:
if ( Movieclip(parent). UNKNOWN_OB开发者_开发技巧JECT .hitTestObject(this) )
trace(UNKNOWN_OBJECT.name);
UNKNOWN_OBJECT in the above example doesn't necessarily have the same data type.
You could iterate over all children of the parent at every frame to see if there's any collision occurring. This is a brute-force check though and if you have lots of objects to check collisions against, I suggest you look into Quadtrees or something similar.
Here's an example how your "box object" could check collisions:
// this is your ENTER_FRAME handler
private function handleEnterFrame(evt:Event):void {
var p:MovieClip = parent as MovieClip;
if(!p){
return;
}
for(var i:int = 0, len:int = p.numChildren; i < len; i++){
var child:DisplayObject = p.getChildAt(i);
if(child != this && this.hitTestObject(child)){
trace("Collides with: " + getQualifiedClassName(p.getChildAt(i)));
}
}
}
All it does is checking collisions with all the child-nodes of the parent (i.e. siblings) every frame. When a collision is detected, it will trace out the class name of the item it collided with. To make this more useful it would be a good idea to dispatch some Event or Signal at the time a collision is detected, so your classes can "listen" for collisions.
精彩评论