Getting RaycastResult Origin and Direction

  1. What do you want to achieve? I need to get the origin and direction of a Raycast

  2. What is the issue? I am recoding an older module that uses Ray.new, which does Ray.Origin and Ray.Direction. I am trying to make it work with the WorldRoot:Raycast() function.

The first two parameters of WorldRoot:Raycast() are the origin and direction, so you can’t directly get it.

The Origin and Direction are parameters that you provide to the Raycast function which then generates a ray and if it hits something provides instance of the object it hit in it’s .Instance property along with providing a .Position property for the position of the hit.

As a quick example, let’s say you want to raycast from the players position, in the direction they are looking that is 500 studs long. Add a few parts to the workspace so there is something to point at and test the raycast. When the ray fires, if it hits something it will add a white ball at the location of the hit.

--Not a great example but hopefully enough.
--LocalScript in StarterPlayer>StarterPlayerScripts

local players = game:GetService("Players") --get the players
local player = players.LocalPlayer --get the local player

task.wait(5) --wait a few seconds, gives the character a chance to load and a small amount of time to move the character befor the ray fires

local char = player.Character --get the player character
local origin = char.PrimaryPart.Position --get the player position
local direction = char.PrimaryPart.CFrame.LookVector --get the direction the player is looking in
local rayLength = 500 --distance in studs to extend the ray, ray is only 1 stud long otherwise

print(player.Name .. " is standing @ " .. tostring(origin))
print(player.Name .. " is looking @ " .. tostring(direction))

local ray = game.workspace:Raycast(origin, direction * rayLength) --cast a ray from the players position, in the direction they are looking, that is 500 studs long

if ray == nil then --nothing was hit
	print("Ray didn't hit anything.")
else --something was hit, print it's name and position
	print("Ray hit: " .. ray.Instance.Name .. " @ " .. tostring(ray.Position))
	local part = Instance.new("Part") --create a new part, anchor it and move it to the hit position
	part.Parent = workspace
	part.Anchored = true
	part.Position = ray.Position
	part.Name = "HitPoint"
	part.Shape = Enum.PartType.Ball
	part.Color = Color3.fromRGB(255, 255, 255)
end