How can I make a raycast from a parts direction?

I found a raycast script on youtube, but it creates a raycast where the mouse is. How can I make a raycast that points from a parts direction/look vector?

You can try this out:

local function CheckFrontSight(start, target)
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {start}
	params.FilterType = Enum.RaycastFilterType.Blacklist

	local vector = start.CFrame.LookVector
	local ray = workspace:Raycast(start.Position, vector * 40, params)

	if ray and ray.Instance then
		warn(ray.Instance.Name)
		if ray.Instance:IsDescendantOf(target.Parent) then
			return true
		end
	end
	return false
end

Uh, so do I put this in a script in a part?

Yeah, then you can do something like this for example:

local part1 = script.Parent
local part2 = workspace.Part2
  
local function CheckFrontSight(start, target)
    local params = RaycastParams.new()
    params.FilterDescendantsInstances = {start}
    params.FilterType = Enum.RaycastFilterType.Blacklist
  
    local vector = start.CFrame.LookVector
    local ray = workspace:Raycast(start.Position, vector * 40, params)
  
    if ray and ray.Instance then
        warn(ray.Instance.Name)
        if ray.Instance:IsDescendantOf(target.Parent) then
            return true
        end
    end
    return false
end
  
while task.wait(.05) do
    if CheckFrontSight(part1, part2) == true then
        warn("no way i can see it")
    else
        warn("awww :(")
    end
end

Well, it works, but this still uses two parts. Is there a way I can just get the part in front of the part?

Sure you can, this code down here just returns any part that it sees on front.

local part1 = script.Parent

local function GetPartsInFrontRay(start)
    local params = RaycastParams.new()
    params.FilterDescendantsInstances = {start}
    params.FilterType = Enum.RaycastFilterType.Blacklist
    
    local vector = start.CFrame.LookVector
    local ray = workspace:Raycast(start.Position, vector * 40, params)
    
    if ray and ray.Instance then
        return ray.Instance
    end
end 
  
while task.wait(.05) do
    local part = GetPartsInFrontRay(part1)
    
    if part then
        warn(part.Name)
    end
end
4 Likes