01 | local start = thisGun.Position |
02 | local lookAt = thisGun.Position + thisGun.CFrame.lookVector* 900 |
03 | --print("This gun is at position "..start.x..","..start.y..","..start.z) |
04 | --print("Looking at position "..lookAt.x..","..lookAt.y..","..lookAt.z) |
05 | local ray = Ray.new(start, (lookAt - start).unit) |
06 | local targetHit, targetHitPos = game.Workspace:FindPartOnRay(ray) |
07 | local targetHitName |
08 | local mag = (thisGun.Position - targetHitPos).magnitude |
09 |
10 | if targetHit ~ = nil and mag < 1000 then |
11 | targetHitName = targetHit.Name |
12 | else |
13 | targetHitName = "nil" |
14 | targetPos = lookAt |
15 | mag = (thisGun.Position - targetPos).magnitude |
16 | 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:
1 | local lookAt = thisGun.Position + thisGun.CFrame.lookVector* 900 |
What you really mean with this line is
1 | 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:
1 | local direction = thisGun.CFrame.lookVector |
2 |
3 | local ray = Ray.new(start, direction.unit * 990 ) |
4 | -- Only values up to 1000 work, but most of the time you want as long as possible |