#raycast snapping into an opposite direction

1 messages · Page 1 of 1 (latest)

heavy violet
#

i have made a laser with basic raycasting, and for some reason the laser snaps into a different direction when playing. when the laser is looking in the right direction the raycast just doesn't work

#
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

wise sequoia
#
--!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

heavy violet
#

this is in the input

wise sequoia
#

No shit

#

My code is not referencing your laser structure. You can figure that out, lol

heavy violet
#

fluckk i just noticed it

#

mn

#

mb

wise sequoia
#

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

spice cave
#

facts my brother

heavy violet
#

thanks for the help!

#

i will try to fix it