Flixel Forums

development => help => Topic started by: Spengler on Sun, May 1, 2011

Title: Hit test for close but non-touching objects
Post by: Spengler on Sun, May 1, 2011
Hi guys. I'm trying to make my first game with Flixel and it's going pretty well. I've got a query though about hit testing objects. I want my character to be able to destroy objects he's stood next to. I tried checking what he was next to using the isTouching method, which is ok, but I don't want the player having to be pressing left or right against the object in order to destroy it when they press hit. Is there a way to check if there is a object say 5 or 10 pixels infront of whichever way he's facing? Like raycasting or something? Or will I have to use the bullet method but limit it to only travelling a few pixels so it doesn't destroy stuff far off in the distance? The latter method seems a bit excessive, having a third object interacting between the player and the object being destroyed.
Title: Re: Hit test for close but non-touching objects
Post by: zadvornykh on Sun, May 1, 2011
If they are on equal x-coordinates, you can loop through the members property of FlxGroup (assuming your objects are in a FlxGroup) and check the distance between each object and the player. If a block is within distance, kill the object.

Something like this:

Code: [Select]
for each(var object:FlxSprite in Objects.members)
{
 if(object.x - player.x <= -10 || object.x - player.x >= 10)
 {
  object.kill();
 }
}

Run the code every time the player presses the appropriate key.

You can augment the code above to account for the way the player is facing.

If the object and the player are not on the same y coordinate, you can use the good old Pythagorean theorem to determine distance (a^2 + b^2 = c^2).
Title: Re: Hit test for close but non-touching objects
Post by: auriplane on Sun, May 1, 2011
You could make an invisible object which tracks the player's location but has a larger size, and test it for collision/overlap.
Title: Re: Hit test for close but non-touching objects
Post by: Spengler on Tue, May 3, 2011
Cheers for the help, got it working.
Title: Re: Hit test for close but non-touching objects
Post by: Adam Atomic on Tue, May 3, 2011
there's also a new fucntion int he latest beta called overlapAt() that might be helpful!