### Author Topic: Hit test for close but non-touching objects  (Read 1498 times)

#### Spengler

• New Member
• Posts: 2
• Karma: +0/-0
##### Hit test for close but non-touching objects
« 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.

• Active Member
• Posts: 205
• Karma: +1/-0
##### Re: Hit test for close but non-touching objects
« Reply #1 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).

#### auriplane

• Snails!!
• Contributor
• Posts: 497
• Karma: +1/-0
• Snails!!
##### Re: Hit test for close but non-touching objects
« Reply #2 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.

#### Spengler

• New Member
• Posts: 2
• Karma: +0/-0
##### Re: Hit test for close but non-touching objects
« Reply #3 on: Tue, May 3, 2011 »
Cheers for the help, got it working.