Page 1 of 1

[]

Posted: Tue Sep 03, 2013 6:43 pm
by bekey
-snip-

Re: Find nearest unobstructed entity using lasers or cone sh

Posted: Tue Sep 03, 2013 6:46 pm
by slime
For something like a laser or bullet you probably want [wiki]World:rayCast[/wiki].

The Box2D manual says this about raycasts (although some details are a bit different for the love.physics wrapper):
You can use ray casts to do line-of-sight checks, fire guns, etc. You perform a ray cast by implementing a callback class and providing the start and end points. The world class calls your class with each fixture hit by the ray. Your callback is provided with the fixture, the point of intersection, the unit normal vector, and the fractional distance along the ray. You cannot make any assumptions about the order of the callbacks.

You control the continuation of the ray cast by returning a fraction. Returning a fraction of zero indicates the ray cast should be terminated. A fraction of one indicates the ray cast should continue as if no hit occurred. If you return the fraction from the argument list, the ray will be clipped to the current intersection point. So you can ray cast any shape, ray cast all shapes, or ray cast the closest shape by returning the appropriate fraction.

You may also return of fraction of -1 to filter the fixture. Then the ray cast will proceed as if the fixture does not exist.

[]

Posted: Wed Sep 04, 2013 10:53 am
by bekey
-snip-

Re: Find nearest unobstructed entity using lasers or cone sh

Posted: Fri Sep 06, 2013 6:09 am
by Rickton
I actually just dealt with a similar problem.
It's probably not terribly efficient, but basically what I did was move along the line, checking to see if there are any objects at each point along the line, until I found something.

I'm also using HardonCollider instead of Box2D, so you'll need to change the part that checks for an object. The first part might help you, though.

Code: Select all

  local xDiff = source.x-target.x --source being the shooter, target being where they're clicking
  local yDiff = source.y-target.y
  local angle = math.atan2(yDiff,xDiff)+math.pi
  local dist = 1
  local newX = source.x + dist*math.cos(angle)
  local newY = source.y + dist*math.sin(angle)
  while dist < maxDist do --my game has a maximum distance the shot can go, if yours doesn't I guess you could check to see if newX or newY is out of bounds or something
    dist = dist+1
    newX = self.source.x + dist*math.cos(angle)
    newY = self.source.y + dist*math.sin(angle)
    for _, shape in ipairs(Collider:shapesAt(newX,newY)) do --this'll need to change since you're not using HardonCollider, but what that function does is check to see what objects are at a given point and returns them as a table
         return shape
    end -- end for
  end -- end while

[]

Posted: Fri Sep 06, 2013 10:42 am
by bekey
-snip-