I have a spinning part with a beam parented to it, I want the beam to go in front of
whatever it hits; therefore, I am using RayCasting. I wrote code to send out a ray that is always in front of the spinning part, but it only detects things it hits at a certain ‘rotation’?
local partA = script.Parent
local beamAtt1 = partA.Attachment1
while task.wait(0.01) do
partA.CFrame *= CFrame.Angles(0, math.rad(1), 0) -- Spin
local rayOrigin = partA.Position
local rayDirection = partA.CFrame.Position -- Shoot out from the spinning part
local raycastResult = workspace:Raycast(rayOrigin, rayDirection)
if (raycastResult) then
beamAtt1.WorldPosition = raycastResult.Position -- Put beam in front of hit
end
end
I am new to RayCasting, so if someone could explain to me what I am doing wrong, I would appreciate it.
Hi there!
I edited your code and your part a little bit to get this result: robloxapp-20220708-2009303.wmv (1.6 MB)
First, I changed partA.CFrame.LookVector to partA.CFrame.LookVector * 100 to give it a range of 100 studs
I also added an attachment into that part for it to serve as the default position of partA.Attachment1
So here’s the full code:
local partA = script.Parent
local beamAtt1 = partA.Attachment1
while task.wait(0.01) do
partA.CFrame *= CFrame.Angles(0, math.rad(1), 0) -- Spin
local rayOrigin = partA.Position
local rayDirection = partA.CFrame.LookVector * 100 -- Shoot out from the spinning part with a range of 100 studs
local raycastResult = workspace:Raycast(rayOrigin, rayDirection)
if (raycastResult) then
beamAtt1.WorldPosition = raycastResult.Position -- Put beam in front of hit
else
beamAtt1.WorldPosition = partA.DefPos.WorldPosition -- Put Attachment1 to its default position
end
end
robloxapp-20220708-1433413.wmv (1.0 MB)
You can see that it keeps its length from the last thing it hit, I tried multiplying the position, but it ends up disappearing while it hits the void, it reappears when it hits a part again.
Strange, mine works perfectly fine and there isn’t any such bug, did you put the ‘DefPos’ Attachment 100 studs (or the range you chose) in front of the part? (sorry for not mentioning that, as I completely forgot it)