#raycast snapping into an opposite direction
1 messages · Page 1 of 1 (latest)
local laserPart = script.Parent.Laser
local att1 = laserPart.start
local att2 = laserPart.target
local param = RaycastParams.new()
param.FilterDescendantsInstances = {laserPart}
param.FilterType = Enum.RaycastFilterType.Exclude
while true do
task.wait()
local rayOrigin = laserPart.Position
local rayDirection = laserPart.CFrame.LookVector * 15000
local ray = game.Workspace:Raycast(rayOrigin, rayDirection, param)
if ray then
local hitPosition = ray.Position
local localHitPos = laserPart.CFrame:PointToObjectSpace(hitPosition)
att2.Position = localHitPos
else
att2.Position = Vector3.new(0, 0, 15000)
end
end```
here is the code
--!strict
local RunService = game:GetService("RunService")
local MAX_LASER_DISTANCE = 15_000
local Laser = script.Parent
local End = Laser.End
local function renderBeam()
local cframe = Laser.CFrame
local origin = cframe.Position
local direction = cframe.LookVector * MAX_LASER_DISTANCE
local result = workspace:Raycast(origin, direction)
local position = nil
if result then
position = result.Position
else
position = origin + direction
end
End.WorldPosition = position
end
RunService.PostSimulation:Connect(renderBeam)
@heavy violet
End is not a valid member of Model "Workspace.PEQ 15 (with code)"
this is in the input
No shit
My code is not referencing your laser structure. You can figure that out, lol
All good
Anyways, your issue was that you did not maintain relativity with your endpoint positioning
In Roblox, the forward direction is negative on the Z axis. Whenever your raycast failed to intersect, you set the endpoint position to 15k studs backwards in world space
If you had rotated the laser attachment along the Y axis, you would have noticed the beam remaining locked
local result = workspace:Raycast(origin, direction)
local position = nil
if result then
position = result.Position
else
position = origin + direction
end
End.Position = cframe:PointToObjectSpace(position)
You needed to calculate the virtual endpoint of the ray with respect to the current forward direction of the laser attachment
facts my brother