Okay, so I’m working on a gun system, and I basically can’t continue working on it until I fix this issue, the problem is that I’m trying to not use mouse.Hit and replace it with an alternative like screenPointToRay or viewportPointToRay, but those have not been working and caused me more issues AND ended up being 10x more complicated than just using mouse.Hit
One of my issues is that my gun was initially firing backwards, but I ended up fixing this, but not even the fix ended up making the bullets fire properly.
Someone suggested that I should increase the length of the viewportRaycast to make it so that this bug doesn’t happen.
Then this happens. You can clearly see the end of the bullet does not match my mouse, this is because the bullet raycast thinks I am trying to hit a spot that the increased-length-viewportRaycast was hitting.
Here is my code for it:
local function fire()
local origin = muzzleAttachment.WorldPosition
local mouseLocation = UserInputService:GetMouseLocation()
local viewportRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
local viewportDirection = viewportRay.Direction * 1500
local viewportRaycast = Workspace:Raycast(viewportRay.Origin, viewportDirection, raycastParameters)
local viewportIntersection = viewportRaycast and viewportRaycast.Position or viewportRay.Origin + viewportDirection
local bulletDirection = (viewportIntersection - origin).Unit * 100
local bulletRaycast = Workspace:Raycast(origin, bulletDirection, raycastParameters)
local bulletIntersection = bulletRaycast and bulletRaycast.Position or origin + bulletDirection
local distanceBulletTraveled = (origin - bulletIntersection).Magnitude
-- VISUALIZATION***
local part = Instance.new("Part")
part.Size = Vector3.new(0.1, 0.1, distanceBulletTraveled)
part.CFrame = CFrame.lookAt(origin, bulletIntersection) * CFrame.new(0, 0, -distanceBulletTraveled / 2)
part.Anchored = true
part.CollisionGroup = "Bullets"
part.CanCollide = false
part.Parent = Workspace
end
I am considering just switching back to mouse.Hit, and there are little to no posts that talk about using UIS and viewportToRay/screenPointToRay for guns.