Change part transparency through raycast

Is there any way with my current code to try and make it so if the raycast hits a part named “Roof” it will change that part’s transparency?

Here is my current code for casting the ray:

while wait() do
	local StartP = game.Workspace.cameraPart.Position
	local EndP = script.Parent.HumanoidRootPart.Position + Vector3.new(0,3,0)
	
	local result = workspace:Raycast(StartP, EndP - StartP)
	
end

HELP!

3 Likes

You will need to make sure that there was a hit part by doing

if result then
    -- there was a result, check name
    if result.Instance.Name == "Roof" then
        -- change the transparency
        result.Instance.Transparency = 0.5 -- or whatever you want
    end
end
2 Likes

I can’t belive it was that simple XD

I was doing:

if result.Name == “Roof” then

Thank you very much!

2 Likes

I have one more question.

Is there a way that I can detect if the ray cast is no longer touching that part and then change the transparency back to 0?

For that you will just need to have a variable that is created outside of the loop, and if there is a hit then set it to true and change the transparency, if there is no longer a hit, then change the transparency back.

local hit = nil
while wait() do
	local StartP = game.Workspace.cameraPart.Position
	local EndP = script.Parent.HumanoidRootPart.Position + Vector3.new(0,3,0)
	
	local result = workspace:Raycast(StartP, EndP - StartP)
	if result then
    -- there was a result, check name
        if result.Instance.Name == "Roof" then
            hit = result.Instance
            -- change the transparency
            hit .Transparency = 0.5 
        end
    else
        if hit then
            hit.Transparency = 0
            hit = nil
        end
    end
end
3 Likes

AGAIN!

I can’t thank you enough! Works flawlessly!

1 Like

So, after looking through your other posts on the DevForum, I think that you may want to look into ZonePlus. With it, you will be able to detect when a player enters and leaves your building, and change the transparency of the corresponding roof. It will look something like this:

local player = game.Players.LocalPlayer
local Zone = require(Path.To.Zone)
local container = Container -- this is going to be a part that covers the entire building
local zone = Zone.new(container)

zone.localPlayerEntered:Connect(function()
    -- the player has entered the building, change the roof transparency
    correspondingRoof.Transparency = 0.8
end)

zone.localPlayerExited:Connect(function()
    -- the player left the building, change the transparency
    correspondingRoof.Transparency = 0
end)
1 Like

It is all good I got it to work so don’t worry :+1:

Thanks anyways though!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.