How to get length of ray

Im using a raycast that starts at the players root part. But I’ve researched on the dev forum and can’t find how I would get the distance between the ground and the player.

game:GetService("RunService").Heartbeat:Connect(function()
	
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude; raycastParams.FilterDescendantsInstances = {char}; raycastParams.IgnoreWater = true
	
	local ray = Ray.new(root.CFrame.UpVector, Vector3.new(0, -10, 0))
	
	-- Im looking for something similar to below
	if ray.Distance == 10 then
		-- DO CODE
	end
	end)
1 Like

(startPosition-endPosition).Magnitude

but i’d like to point out that that can’t exactly be done with your code

1 Like

What do I need to add to the code?

your origin is a direction while your direction is an arbitrary vector3

2 Likes

How would I get the end point though? I don’t see that in the documentation?

Why not use Workspace:Raycast()? it is recommended over Ray.new() and has a built in length/distance variable.

local pos = Vector3.new(0,0,0)
local dir = Vector3.new(0,1,0) * 1000

local cast = workspace:Raycast(pos, dir)

if cast then
	print(cast.Distance)
end

I also dont think Ray.new() has a .Distance variable.

1 Like

Yes, I had realized that in the documentation and i’ve changed it to.

local function castRay()
	-- The origin point of the ray
	local originPosition = root.Position
	-- The direction the ray is cast in
	local direction = -Vector3.yAxis
	-- The maximum distance of the ray
	local distance = 10

	-- Cast the ray and create a visualization of it
	local raycastResult = game.Workspace:Raycast(originPosition, direction * distance)

	if not raycastResult then

		local velocity = Instance.new("LinearVelocity", char:WaitForChild("HumanoidRootPart"))
		local Attachment = Instance.new("Attachment", char:FindFirstChild("HumanoidRootPart"))
		Attachment.Name = "glideAttatch"
		velocity.Name = "glideVelocity"
		velocity.MaxForce = math.huge
		velocity.VelocityConstraintMode = Enum.VelocityConstraintMode.Vector
		velocity.Attachment0 = Attachment
		velocity.RelativeTo = Enum.ActuatorRelativeTo.Attachment0
		Attachment.WorldPosition = char:FindFirstChild("HumanoidRootPart").AssemblyCenterOfMass
		velocity.VectorVelocity = Vector3.new(0,-5,-25)
		
	else 
		local glideAttach = root:FindFirstChild("glideAttach") 
		local glideVelocity = root:FindFirstChild("glideVelocity")
		if glideAttach  or glideVelocity then
			glideAttach:Destroy()
			glideVelocity:Destroy()
		end
	end
end

game:GetService("RunService").Heartbeat:Connect(function()
	castRay()
	end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.