How would I measure the distance between the start of a ray and where it hit an object?

Back with another problem already haha

I’ve tried using the position of the object the ray hit, but then it’s innacurate because it measures from the center of the object that was hit, instead of where it was hit by the ray. I don’t know any other way i would do this.

Here’s a video of what’s happening with the gun: 2023-08-23 13-20-45
The bullet goes through objects, though I need it to stop when it hits one.

Here’s what I have thus far:

-- direction = (endPos - startPos).Unit * 100
-- If the rayInstance exists, I need to make the direction the length of between the startpos and object --- that the ray hit as I said before. If not, the bullet just goes 100 studs.

local function CreateVisual(startPos, direction, rayInstance, endPos, rayPos)
	local center = startPos + direction / 2
	local distance = direction.Magnitude
	
	local part = Instance.new("Part")
	part.Parent = visuals
	part.Anchored = true
	part.CanCollide = false
	part.Color = Color3.fromRGB(255, 255, 255)
	part.Material = Enum.Material.Neon
	
	part.CFrame = CFrame.new(center, startPos)
	part.Size = Vector3.new(0.15, 0.15, distance)
	game.Debris:AddItem(part, 0.1)
end

Please help, I’ve been stuck with this problem for a while now.

I ended up figuring it out by doing this:

local function CreateVisual(startPos, direction, rayDistance, endPos)
	
	if rayDistance then
		local distance = (rayDistance - startPos).Magnitude
		direction = (endPos - startPos).Unit * distance
	end
	
	local center = startPos + direction / 2
	local distance = direction.Magnitude
	
	local part = Instance.new("Part")
	part.Parent = visuals
	part.Anchored = true
	part.CanCollide = false
	part.Color = Color3.fromRGB(255, 255, 255)
	part.Material = Enum.Material.Neon
	
	part.CFrame = CFrame.new(center, startPos)
	part.Size = Vector3.new(0.15, 0.15, distance)
	game.Debris:AddItem(part, 0.1)
end
1 Like

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