I’m making a raycast gun and it is working, yet the when I visualize the raycast using a part, it doesn’t work as intended. I use the midpoint formula to move the part to the midpoint of the ray, yet I relaise that hey? Aren’t rays practically infinite? (citation needed) And the part spawns in the midpoint, yet can’t be extended farther to the gun itself.
So is there a way I can shorten a ray to a finite length? Or am I doing something scripting wise?
Clarify:
origin: part of the gun’s position
direction: mouse position * 10 (like a max size of the laser is 10, yet idk if i did that right)
function visualize (raycastResult)
local midpoint = raycastResult.Origin + raycastResult.Direction/2
local part = Instance.new("Part")
part.Anchored = true
part.CFrame = CFrame.new(midpoint, raycastResult.Origin)
part.Size = Vector3.new(1,1, raycastResult.Direction.magnitude)
part.Material = Enum.Material.Neon
part.Color = Color3.new(1, 1, 0)
part.Parent = workspace
end
Update:
Ok weird stuff is happening. Sometimes it works and sometimes it doesnt. I’m still not sure what is wrong, I get no error messages.
I’m pretty sure Gizmo can help visualize raycasts.
This is the post that someone made, it also supports raycast visualization, though you need to use an arrow if you want it to tell how far the raycast has been going.
Calculate the magnitude from the origin and probably use CFrame.lookAt() instead:
local magnitude = (raycastResult.Origin - raycastResult.Direction).Magnitude
part.CFrame = CFrame.lookAt(midpoint, originPart.Position) --CFrame.lookAt() works the same as CFrame.new()'s second argument but properly made for looking, I would say it's better practice to use this instead
part.Size = Vector3.new(1,1, magnitude)
Also if these are going to be your bullets make sure to use something like PartCache as creating a lot of parts so quickly with Instance.new() can be very expensive.
Is the visualizing part working properly though? Is it only creating multiple parts? If so then you’re going to have to share more of your code since that means the function is being called multiple times.
Well how it works is that the function is called, by tool.activated and then ya. So sometimes I click what I describe happens above, or when I click it works as intended.