hey guys, the other day I was watching a tutorial on how to make rays visible using parts by B Ricey, it was a pretty good video until I saw that he was using the deprecated raycasting system (original video: How to make Raycasting Visible using Parts - Roblox Studio - YouTube)
I tried implement the concept into the new raycasting system, but it didn’t turn out as I expected… My code:
local origin = script.Parent.Position
local direction = (script.Parent.CFrame.LookVector * -1) * 20
function MakePartVisible(raycastResult)
local part = Instance.new("Part", workspace)
part.Anchored = true
part.CFrame = CFrame.new(origin, direction)
part.Size = Vector3.new(1, 1, direction.Z)
part.Material = Enum.Material.Neon
part.BrickColor = BrickColor.Red()
return part
end
local raycastResult = workspace:Raycast(origin, direction)
MakePartVisible(raycastResult)
This has something to do with positioning your ray.
In order to achieve what the video has shown, you must understand two things:
Where is the ray facing?
What is the desired position?
Your code basically positions the ray part to the origin, which is not wrong, but the wrong part here is how it is being positioned. By default, Roblox positions parts with respect to the center of a part. The center of a part is usually the midpoint of each dimension length of the part, hence your part is positioned such so.
To solve this problem, the best way is to position the part somewhere that is at the middle of its raycast direction:
This tutorial is on the official Roblox studio help page, it’s pretty long but I’m sure that there’s something about making the raycast visible in there because I followed the tutorial. Hit Detection with Lasers | Roblox Creator Documentation
I have done much with this before. I recommend you use a LineAdornee as you don’t have to mess with CFrames.
Anyways, this is some old code that you may want to use. I would recommend you only use it for debugging.
local raycastView = Instance.new("Part")
raycastView.Anchored = true
raycastView.CanCollide = false
raycastView.CanQuery = false
raycastView.CanTouch = false
raycastView.CastShadow = false
local function visRay(startPosition,direction,colour)
local endPosition = startPosition + direction
local midpoint = (startPosition + endPosition) /2
local ray = raycastView:Clone()
ray.Parent = workspace
ray.Size = Vector3.new(0.2,0.2,direction.Magnitude)
ray.CFrame = CFrame.lookAt(midpoint,startPosition)
Debris:AddItem(ray,0.1)
--Ignore this if you do not care about the colour :)
if colour == "red" then
ray.BrickColor =BrickColor.new("Really red")
elseif colour == "green" then
ray.BrickColor =BrickColor.new("Bright green")
elseif colour == "blue" then
ray.BrickColor = BrickColor.new("Bright blue")
elseif colour == "violet" then
ray.BrickColor = BrickColor.new("Bright violet")
end
ray.Material = "Neon"
end
The difference is that you have to set your CFrame to the midpoint between the origin and the destination.