Raycasting and distances

Hey there, Fusioncore21 back at it again!
Alright, so recently I have been looking at Rays for a game prototype I have been working on.
Now, the idea is that I have a laser and a mirror. The laser sends out a ray towards anything in front of it. I already have the ray emitting thing working, but all I am coming to you for is to figure out how to find the distance of how far the ray had to travel before hitting the part I want. I looked on the API but it does a really bad job of explaining it for me.
Here is my code which is really badly formatted, sorry.

local whitelist = workspace.GameEnvironment.Game1.ImportantStuff:GetChildren()
local Ignore = workspace.AlphaLaser
wait(0.5)
local Col = Ray.new(workspace.AlphaLaser.Emitter.Position,workspace.AlphaLaser.Emitter.CFrame.RightVector.Unit*100)

Collison = workspace:FindPartOnRayWithWhitelist(Col,whitelist)
--Point = Col:Distance(Col:ClosestPoint()) -- This didn't work when I tried it
print(Collison.Parent)

Any help would be appreciated. :slight_smile:
Thanks.

2 Likes

workspace:FindPartOnRay() and its similar functions return multiple things. Doing the following line:
local hit, hitposition, normal = workspace:FindPartOnRayWithWhitelist(Col, whitelist) will get you all that you need.

hit will be the part that the ray struck. It will return nil if it hits nothing.
hitposition will be the Vector3 position where hit was struck - this is what you will need
normal can be used to figure out what direction is parallel to where hit was struck - useful for stuff like bulletholes

In order to get the distance a ray has travelled, do this: local Distance = (MyOrigin - hitposition).magnitude. Just replace MyOrigin with the Vector3 of where your ray starts.

8 Likes

Now that is something the wiki didn’t tell me!
Thanks for this, really helps. :slight_smile:

2 Likes