Basically, I'm trying to send three raycasts out from the character, each at a different angle. As you can see in this picture, one ray is supposed to go straight out which I can do with ease, but the outside rays are supposed to be angled and sometimes turn out wrong. You can see what I mean by turn out wrong in this gif. The third and fourth times the beams appear is what it's intended to look like, and all the other times are errors.
This is my code
function rotatedVector (vector , theta) local x = vector.X * math.cos(theta) - vector.Z * math.sin(theta) local z = vector.X * math.sin(theta) + vector.Z * math.cos(theta) return Vector3.new(x , vector.Y , z) end for i = 1,3 do local theta = math.rad(30) --angle in radians local lookVector1 = char.HumanoidRootPart.CFrame.lookVector * 5 local lookVector2 = rotatedVector(lookVector1 , theta) local lookVector3 = rotatedVector(lookVector1 , -theta) local rayEnd if i == 1 then rayEnd = lookVector1 elseif i == 2 then rayEnd = lookVector2 elseif i == 3 then rayEnd = lookVector3 end local ray = Ray.new(char.HumanoidRootPart.Position, rayEnd) -- I've also tried using "char.HumanoidRootPart.CFrame.Position" but as expected nothing changes local part, position = workspace:FindPartOnRay(ray, char, false, true) local beam = Instance.new("Part", workspace) beam.BrickColor = BrickColor.new("Bright red") beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0 beam.Anchored = true beam.Locked = true beam.CanCollide = false local distance = maxDistance beam.Size = Vector3.new(0.3, 0.3, distance) beam.CFrame = CFrame.new(char.HumanoidRootPart.CFrame.p, position) * CFrame.new(0, 0, -distance / 2) game:GetService("Debris"):AddItem(beam, 1) end
Any help would be appreciated.
The probelem I've identified that's most likely causing the issue is the lookAt
parameter you are using to construct the CFrame for your beams. You are using the position of the humanoid root part and the position of the ray intersection which is the wrong way to do this. You should be using the lookVector
instead of the ray intersection point. The positioning of the part should now look something like this:
local pos = char.HumanoidRootPart.CFrame.Position local lookAt = char.HumanoidRootPart.Position + rayEnd local offset = CFrame.new(0, 0, -distance / 2) beam.CFrame = CFrame.new(pos , lookAt) * offset
I've tested specifically using the code you posted in your question and I encountered the same issue. Upon implementing the fix, the problems went away.