Bullet fires to my camera?

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.

2 Likes

It is indeed because the distance from your camera to the raycast origin exceeds the raycast length, to fix it you can simply add the distance of the camera to the character to the original raycast length

2 Likes

Can you explain what you mean by this or show an example because wouldn’t this interfere with how far I want to make the bullet go?

I still dont get what you mean by this??? this would also mess up my travelDistance variable aswell.

local dist = (currentCamera.CFrame.Position - viewportRay.Origin)
local viewportDirection = viewportRay.Direction * travelDistance + dist

You can increase the length of the ViewportRay (only that, not the other Raycast) to 15000 and it’ll fix the problem, and no this won’t mess up the actual Travel Distance since the ViewportRay only determines where the BulletRaycast should point to (basically mouse.Hit.Position) and BulletRaycast is the actual part that determines what the bullet hits

1 Like

Okay, so, I see what you are trying to do here, but it causes the bullet to be inaccurate because it thinks it is using the length of the other raycast

Actually, just use this for the bullet direction

CFrame.new(Camera.CFrame.Position,Camera.CFrame.Position+Mouse.Hit.LookVector*100).LookVector * BulletLength
1 Like