I’m working on raycasting to make a simple first-person gun shooting logic. Sometimes laser goes in a weird direction instead of working properly. It feels like my ray overlaps with something and points towards my head.
how it should work:
the bug:
local uis = game:GetService("UserInputService")
local Players = game:GetService("Players")
local pistol = script.Parent
local rayModule = require(game.ReplicatedStorage.RayModule)
local MAX_MOUSE_DISTANCE = 1000
local MAX_LASER_DISTANCE = 500
local function getWorldMousePos()
local mouseLoc = uis:GetMouseLocation()
local screenToWorldRay = workspace.CurrentCamera:ViewportPointToRay(mouseLoc.X, mouseLoc.Y)
local directionVector = screenToWorldRay.Direction * MAX_MOUSE_DISTANCE
local rayRes = workspace:Raycast(screenToWorldRay.Origin, directionVector)
if rayRes then
return rayRes.Position
else
return screenToWorldRay.Origin + directionVector
end
end
local function fireWeapon()
local mouseLoc = getWorldMousePos()
local targetDirection = (mouseLoc - pistol.Handle.Position).Unit
local directionVector = targetDirection * MAX_LASER_DISTANCE
local weaponRayParams = RaycastParams.new()
weaponRayParams.FilterDescendantsInstances = {
Players.LocalPlayer.Character,
workspace.BulletFolder:GetChildren()
}
local weaponRayRes = workspace:Raycast(pistol.Handle.Position, directionVector, weaponRayParams)
local hitPos
if weaponRayRes then
hitPos = weaponRayRes.Position
local charModel = weaponRayRes.Instance:FindFirstAncestorOfClass("Model")
if charModel then
local humanoid = charModel:FindFirstChild("Humanoid")
if humanoid then
print("PLAYER HIT")
end
end
else
hitPos = pistol.Handle.Position + directionVector
end
rayModule.createLaser(pistol.Handle, hitPos)
end
local function toolEquipped()
end
local function toolActivated()
fireWeapon()
end
pistol.Equipped:Connect(toolEquipped)
pistol.Activated:Connect(toolActivated)