Skip to main content
chienbleu
Known Participant
May 19, 2023
Answered

AS3: How do I do collision with multiple instances?

  • May 19, 2023
  • 28 replies
  • 2291 views

I know I already asked a few months ago but I wasn't specific enough and had less coding expirience. I don't know how to code in a class so I want to code in a keyframe if that makes sense.

I want to have a thing that can collide with a bunch of squares that I added to stage through code. The only way I know how to do this is by painstakingly dragging each instance to the stage and giving it another name and using multiple hitTestObject but I don't want to do that.

This would be very helpful for things like a catcher game, flappy bird, snake game, etc. What is the best way to do this?

This topic is closed to new replies. Start a new post to keep the conversation going.
Correct answer kglad

tha tshould work


you only use the hittest when creating a square.  you probably want to start a loop (eg, enterframe) when dragging and perform hittests.

28 replies

kglad
Community Expert
Community Expert
May 19, 2023

one way; add the elements to an array and loop through the array using your hittestobject. eg,

 

var a:Array = [];

var sqNum:int = 22;

 

for(var i:int=0;i<sqNum;i++){

createSquareF();

}

 

function createSquareF():void{

var sq:MovieClip = new Square(); // linkage id

// add to stage, position etc

a.push(sq);

}

 

function hitTestF():void{

for(var i:int=a.length-1;i>=0;i--){

if(yourthing.hitTestObject(a[i])){

// do whatever. loop backwards if you are "destroying" a elements and want to remove them from the array.

}

}

}

chienbleu
chienbleuAuthor
Known Participant
May 20, 2023

ok, i adjusted it and there is no errors except one saying the paramater must be non-null or a weirder one where  i said the popping value to 1 and "Property 1 not found on builtin.as$0.MethodClosure and there is no default value." however it's not doing anything at all. here's the code

 

var aaa:Array = [];
var sqNum:int = 10;
 
for(var i:int=0;i<sqNum;i++)
{
createSquareF();
}
 
 
function createSquareF():void
{
var squarey:square = new square(); 
addChild(squarey)
squarey.x = (Math.random()* 669)
squarey.y = (Math.random()* 420)
aaa.push(squarey);
if (thing.hitTestObject(aaa[i]))
{
removeChild(squarey)
aaa.pop[1]
}
}
 
 
 
function hitTestF():void
{
for(var i:int=aaa.length; i>=0;i--)
{
if(thing.hitTestObject(aaa[i]))
{
trace("ad")
}
}
}
chienbleu
chienbleuAuthor
Known Participant
May 20, 2023

actually ignore the pop because i actually just made  thesquare move somewhere else rather than deleting it. there's no errors