[AS3] HitTestPoint Array Issue

6 posts

Flag Post

We are having a bit of a weird issue when looping through an array to find a point collision. We use a recursive method to draw a laser that breaks when it hits a wall. This works fine when we use one wall:

if(wall.hitTestPoint(endX + laser.x,endY + laser.y,true))
{
	break;
}

But if we store all our walls in an array it doesn’t seem to work. We looked if the array was properly setup, and this is correct. When we put a single wall in the array and gave it an variable aswell, the following piece of code confirmed that it works fine.

if(wallArray[i] == wall)
{
	trace("ok");
}

Yet the following example does not seem to work in any way, it never returns a hit even when only one wall is in the array and the above parameter has been met.

for(var i in wallArray)
{
							
	if(wallArray[i].hitTestPoint(endX + laser.x,endY + laser.y,true))
	{
		break;
	}
}

Is there some sort of compability issue between hitTestPoint and objects in an array? Did we make any oversight or is there a solution for this problem?

Cheers!

 
Flag Post

How is the array declared. You might need to cast out of it:

if(DisplayObject(wallArray[i]).hitTestPoint( ... ))
 
Flag Post

That doesn’t seem to work, thanks though! :)

The array is declared like this:

public var wallArray:Array = new Array();

Then the wall MC’s are drawn using Flash’s draw api and added to the array. Works fine with anything, also works fine when using algebra based hittesting. Which is why we are baffled by this issue.

When we exclude the for loop from the code any simple use this it seems to work fine.

if(wallArray[0].hitTestPoint(endX + laser.x,endY + laser.y,true))
{
	break;
}

On a side note, i isn’t used so that’s not the issue.

 
Flag Post

How bizarre.

What about

for each(DisplayObject thisWall in wallArray){
 if(thisWall.hitTestPoint(...))

… or declare the type of i (which you should do anyway):

for(var i:Integer in wallArray){ ...

… or

for(var i:Integer in wallArray){
 var thisWall:DisplayObject = wallArray[i];
 if(thisWall.hitTestPoint(...))
 
Flag Post

Your initial loop is fine, the problem is that…

for(var i in wallArray)

i there is not an integer. I believe it is a DisplayObject.

 
Flag Post
Originally posted by Draco18s:

Your initial loop is fine, the problem is that…

for(var i in wallArray)

i there is not an integer. I believe it is a DisplayObject.

Actually, it’s a String I believe (key to any dynamic property).


On topic, what you want is a for each loop or a regular for loop.
Try this:

for(var i:int = 0; i wallArray.length; ++i)
{
							
	if(wallArray[i].hitTestPoint(endX + laser.x,endY + laser.y,true))
	{
		break;
	}
}

or

for each (var wall:DisplayObject in wallArray)
{
							
	if(wall.hitTestPoint(endX + laser.x,endY + laser.y,true))
	{
		break;
	}
}