Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Issues with Raycasting; am I doing this right?

		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?

1 answer

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

3 comments

0

Ahhhhh wonderful; I'll give that a try later. Thank! And thanks for the style note; but I already knew that. It was just a hack to see if I could get it to work at all. I'm sure you understand that, with your extensive coding background ;)

0

Just to clarify, the ray can still have a maximum length of 1000, as per the wiki article, correct?

0

Yes, 1000 is fine. Larger values it will accept too, but they will be effectively reduced to length 1000, and it will put an error in the output (so that's not desirable). I like to err slightly shorter just to be safe, but it's not necessary.

This discussion is preserved as it was. New answers, comments, and votes are closed.