This project has moved and is read-only. For the latest updates, please go here.

Determining the collision point for a "laser beam"

Topics: User Forum
Jan 5, 2009 at 2:15 PM
First off, thanks for an amazing library. I managed to knock up a pretty impressive prototype of my game in less than a day, thanks to Farseer's ease of use!

In my game, I'm now trying to implement a laser beam, fired from the player's ship. In order to do this, I need to calculate the point at which the beam would first hit an object in the world, in order to draw a line from the front of the ship to this point.

I tried to do this by creating an invisible Geom, a long thin rectangle coming out of the front of the ship. I then get every contact from the collisions that occur on that rectangle each frame, and I pick the closest one to the ship. I was hoping that would give me the point at which the rectangle first "hits" any other geometry in the world.

What it actually seems to give me is a point at the very end of the rectangle, which could very well be inside other geometries. Is there a way to find out the information I need, i.e. the point at which a laser beam fired from the front of the ship would first hit an object?
Jan 5, 2009 at 9:02 PM
I do not know all the details, so what I will say might not apply. A simple workaround to achieve about the same effect is to draw a line between the centers of the two objects and make the line draw below the objects using the z-index or something similar. This way the line will appear to hit the border of the object. Hope this works for you. 

Regarding the neareast point of a complex object relative to a certain point, I am facing the same issue, hope someone can come with some hints.
Jan 5, 2009 at 9:56 PM
Edited Jan 5, 2009 at 10:27 PM
What you both need is probably ray casting (info here - Edit: Called raycast on most physics forums if I'm not mistaken.). I hope we can get something like ray casting into Farseer Physics in the near future.
Jan 6, 2009 at 12:15 AM
Thanks for the pointers, I guessed that ray casting was the way to go, but I hoped there would be an easier way than implementing it myself. Using Farseer has made me lazy - it makes development so easy that I'm not used to doing any of the work myself.  :)

As it happens, I did find a workaround that's done the trick for now. I've created my rectangular Geom (as described above) but as a poly with loads of vertices (one every few pixels), so there's plenty of places for collisions to happen. I'm sure this is a terribly inefficient way of going about it, and maybe it'll come back to haunt me as the game levels get more complex, but for now the performance seems perfectly acceptable.

Thanks again for all the work you've put into Farseer, it's an absolute godsend!