hello!! lately i’ve been working on a gun system just for fun but i’ve been getting stuck with raycasting.
What is the problem?
the fired raycast sometimes doesn’t register and returns nil. this happens when i generally shoot.
for example when the raycast hits the ground or a npc it doesn’t register.
also, at a certain position the raycast ignores parts, going straight through them. this also returns nil even though, visually, the bullet goes straight through and can be seen clearly colliding.
here’s some screenshots:
i’ve searched through the dev forum but i still can’t figure this out.
any help would be greatly appreciated!!
here’s some code:
Client Side:
local function raycastInfo(inputPosition, maxDistance)
local ray = cam:ScreenPointToRay(inputPosition.X, inputPosition.Y)
ray = Ray.new(ray.Origin, ray.Direction * maxDistance)
local hit = workspace:Raycast(ray.Origin, ray.Direction, params)
if hit then
local calcDir = (hit.Position - firePart.Position) -- no need to turn into .Unit form
local finalRay = Ray.new(firePart.Position, calcDir)
return finalRay
else
return nil
end
end
uis.InputBegan:Connect(function(input, gp)
if gp then return end
if not equipped then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
local info = raycastInfo(input.Position, 100)
if info then
shootEvent:FireServer(mouse.Hit.Position, 100, info.Origin, info.Direction)
end
end
end)
Server Side:
shootEvent.OnServerEvent:Connect(function(player, mousePos : Vector3, dist, origin, dir)
if not equipped then return end
print("shoot event")
--
fireSound:Play()
--
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = {player.Character}
local result = workspace:Raycast(origin, dir, params)
print("pass debounce")
--
if result then
--print(result, result.Instance)
--
local origin2 = firePart.Position
local target = result.Position
local length = (target - origin2).Magnitude
local part, ball = makePart()
part.Parent = player.Character
part.CFrame = CFrame.lookAt(origin2, target) * CFrame.new(0, 0, -length / 2)
part.Size = Vector3.new(part.Size.X, part.Size.Y, length)
spawn(function()
ball.Parent = player.Character
ball.Position = result.Position --result.Position
for i = 1, 0, -0.1 do
ball.Transparency = i
--
task.wait(0.025)
end
end)
game.Debris:AddItem(part, 0.2)
game.Debris:AddItem(ball, 0.2)
end
end)