[]
Posted: Tue Sep 03, 2013 6:43 pm
-snip-
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.
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