Hello, I’m working on a gun system, and right now I’m trying to make the basic raycasting for the gun using UserInputService instead of :GetMouse()
, to do this I am using :ViewportPointToRay()
. The problem with my current code is that once I set my travelDistance
variable to a value like 100, the bullets will start firing to my camera, like this:
I believe the reason for this is when the length of the ray where it SHOULD cast is longer than the distance from my camera to the origin point (i.e. the muzzle of the gun), and it somehow ends up casting the ray to my camera.
CODE:
local travelDistance = 100
local origin = muzzleAttachment.WorldPosition
local mouseLocation = UserInputService:GetMouseLocation()
local viewportRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
local viewportDirection = viewportRay.Direction * travelDistance
local viewportRaycast = Workspace:Raycast(viewportRay.Origin, viewportDirection, raycastParameters)
local viewportIntersection = viewportRaycast and viewportRaycast.Position or viewportRay.Origin + viewportDirection
local bulletDirection = (viewportIntersection - origin).Unit * travelDistance
local bulletRaycast = Workspace:Raycast(origin, bulletDirection, raycastParameters)
local bulletIntersection = bulletRaycast and bulletRaycast.Position or viewportIntersection
local distanceBulletTraveled = (origin - bulletIntersection).Magnitude
If it helps: When I set the travel distance to a higher value like 300, this does not occur and everything will work as normal.