PDA

View Full Version : [AS3] Collision detection


johnrich85
03-11-2010, 06:21 PM
I've made a loop which will create a random number of asteroids, and a function which will create a lazer when space bar is pressed, the lazer is then added to a container.

Im attempting to get collision detection working between the two but cant get it to work. I know hit test object isnt the best way to do it, but should the code below work ?


public function mainGame(evt:Event):void {
// collision *************************
//for every child in the LAZER container
for (var a:Number=0; a < this.shotContainer.numChildren; a++) {
//make variable for current lazer
b = this.shotContainer.getChildAt(a) as J_lazer;

//for every child in the ASTEROID container
for (var c:Number=0; a<this.container.numChildren; a++) {
//make variable for current asteroid
d = this.container.getChildAt(c) as J_asteroid;

if (this.d.hitTestObject(this.b)) {
trace('hit');
} else {
trace('nope')
}

}
}
}

johnrich85
03-11-2010, 06:21 PM
Enter framt event calls the function by the way

TomMalufe
03-11-2010, 07:03 PM
it would be faster to itterate through an array of astroids and an array of lazers rather then doing getChildAt() Otherwise that will probably work. Have you tested it yet?

I found a really cool hittest class [google ws.tink.display.HitTest;] that does a pixel perfect hittest on 2 objects while ignoring alpha. It's nice if you have a square bitmap of a spaceship flying around (or a car in my case) and you want to hittest the ship and not the bitmap.

It should be safe to use in any case because it does a simple fast hittest first and progressively gets more complex only if the tests are true. This way it's not working the CPU more then it has to.

johnrich85
03-11-2010, 07:18 PM
it would be faster to itterate through an array of astroids and an array of lazers rather then doing getChildAt() Otherwise that will probably work. Have you tested it yet?

I found a really cool hittest class [google ws.tink.display.HitTest;] that does a pixel perfect hittest on 2 objects while ignoring alpha. It's nice if you have a square bitmap of a spaceship flying around (or a car in my case) and you want to hittest the ship and not the bitmap.

It should be safe to use in any case because it does a simple fast hittest first and progressively gets more complex only if the tests are true. This way it's not working the CPU more then it has to.

Cheers ill check it out. This is for a uni project, we havent got around to covering arrays yet so would prefer not to use it if possible. I have tried it, it seems like it works occasionaly, possible only for the first asteroid? Other than that it doesnt appear to work.