local start = thisGun.Position local lookAt = thisGun.Position + thisGun.CFrame.lookVector*900 --print("This gun is at position "..start.x..","..start.y..","..start.z) --print("Looking at position "..lookAt.x..","..lookAt.y..","..lookAt.z) local ray = Ray.new(start, (lookAt - start).unit) local targetHit, targetHitPos = game.Workspace:FindPartOnRay(ray) local targetHitName local mag = (thisGun.Position - targetHitPos).magnitude if targetHit ~= nil and mag < 1000 then targetHitName = targetHit.Name else targetHitName = "nil" targetPos = lookAt mag = (thisGun.Position - targetPos).magnitude end
This is the code I've currently got; the code which actually creates the raycasted line is later, and all works correctly; the issue I'm having is that targetHit
and targetHitPos
are always nil and the point that is 1 unit in front of the gun. Did I do something incorrect in creating the ray that is creating a ray with length of 1?
ROBLOX uses a weird definition of ray.
More accurately, Ray.new
describes a segment of space -- from a particular point, to a particular point -- the ray stops after the length is done.
Since you are constructing it with a .unit
vector, the Ray will only look 1 stud (the length of a unit vector) in that direction (and anything after it will pretend it doesn't hit).
Drop the .unit
and that should work fine.
Style note:
local lookAt = thisGun.Position + thisGun.CFrame.lookVector*900
What you really mean with this line is
local lookAt = start + thisGun.CFrame.lookVector*900
This is better because you have to change less code if you tweak the start position; it also makes it clearer what you're doing, because later you use lookAt
only as (lookAt - start)
.
Since you're only subtracting start
after adding it, you might as well remove that and clean things up a bit:
local direction = thisGun.CFrame.lookVector local ray = Ray.new(start, direction.unit * 990 ) -- Only values up to 1000 work, but most of the time you want as long as possible