local function fire()
local bulletSpread = tool:GetAttribute("BulletSpread")
local mouseLocation = UserInputService:GetMouseLocation()
local unitRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y + GuiService:GetGuiInset().Y)
local raycastResult = Workspace:Raycast(tool.Handle.Position, unitRay.Direction * 100)
local intersection = raycastResult and raycastResult.Position or tool.Handle.Position + unitRay.Direction * 100
local distance = (tool.Handle.Position - intersection).Magnitude
local bulletTracer = Instance.new("Part")
bulletTracer.Size = Vector3.new(0.15, 0.15, distance)
bulletTracer.CFrame = CFrame.lookAt(tool.Handle.Position, intersection) * CFrame.new(0, 0, -distance/2)
bulletTracer.Anchored = true
bulletTracer.Parent = Workspace
end
I’m trying to replace mouse.Hit.Position in my gun system using screenPointToRay, but I just cant figure out how to get it to work properly? (Also ignore some of the messy code)
It works slightly better (??), but when it comes to shooting at a low angle (2nd image) it doesnt give me the results im hoping for
local function fire()
local bulletSpread = tool:GetAttribute("BulletSpread")
local mouseLocation = UserInputService:GetMouseLocation()
local unitRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y - GuiService:GetGuiInset().Y)
local raycastResult = Workspace:Raycast(tool.Handle.Position, unitRay.Direction * 100)
local intersection = raycastResult and raycastResult.Position or tool.Handle.Position + unitRay.Direction * 100
local distance = (tool.Handle.Position - intersection).Magnitude
end
When I dont do anything with the gui inset, here’s what it looks like: local unitRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
I believe your problem comes from the fact that the raycast origin is the tool and not the camera. Its only going to appear correct if the part starts at the camera, because the direction created by the unitRay is relative to the camera, not the tool.
Yea, that’s what I was thinking, but my goal is to make it look like it comes from the handle (it will be polished later, but im just testing), any ideas on how to fix this offset?
I think the easiest way is to raycast twice: Once to get whatever the hit position is at the center of the screen, and once to see if the tool could hit that position from its own position.
If there isnt an initial hit position at the center of the screen, then the tool could just use a best guess angle to raycast towards, which doesnt seem like a big deal since you are likely aiming at the sky at that point.
I am sure there is a more complex way you could figure this out with math, but I dont know it.