I am currently trying to make myself a raycasting system for my new gun system, but it is not working how I want. Every time that I cast the ray it is off by about half a stud from where I want it to cast. I have been trying to figure out the problem, but I can’t find it.
I have a script to visualize each cast.
this part puts the cast exactly where I want it to be, no raycasting involved:
-- arg1: start pos, arg2: end pos
-- the last arg is the color so that it stands out
bulletVisualizer.visualizeCast(workspace.TestShooter.Attachment.WorldPosition, nextTarget, BrickColor.Green())
this puts the bullet where I am trying to get it to go.
-- this part visualizes the other cast
local unitRay = Ray.new(
workspace.TestShooter.Attachment.WorldPosition,
workspace.Targets.Targets["25"].Position
)
local hitPos, result = raycaster.getHitPosition(
workspace.TestShooter.Attachment.WorldPosition,
unitRay,
testMaxLength
)
bulletVisualizer.visualizeCast(baseRay.Origin, result.Position)
this however is off by less than half a stud:
-- in a server script
-- arg1: the start Position, arg2: a unit ray for the direction
-- arg3: max length of the ray. is 25 because test brick is
-- exactly 25 studs away.
local hitPos, result = raycaster.getHitPosition(
workspace.TestShooter.Attachment.WorldPosition,
unitRay,
testMaxLength
)
-- in raycast.lua
function module.raycast(startPos, unitRay, maxDist )
-- do the actual raycast
local result= workspace:Raycast(startPos.Unit, unitRay.Direction * maxDist)
-- if there is a result, we hit something
if result then
return result
end
-- no result, nothing hit
return nil
end
-- get a supposed hit position, even if nothing is hit
function module.getHitPosition(startPos, unitRay, maxDist )
local result = module.raycast(startPos, unitRay, maxDist)
-- the ray did in fact hit something
if result then
return result.Position, result
end
-- the ray did not hit anything, manually do math
return unitRay.Origin + unitRay.Direction * maxDist, nil
end
Here is the result:
I cannot figure out what the cause of the small displacement is? Any help?