CurrentCamera:ScreenPointToRay() not working in a specific place

I’m working on making a gun mobile-compatible. The main thing is having a fire button instead of shooting toward the mouse position. I have the code written, and it uses CurrentCamera:ScreenPointToRay(viewportX / 2, viewportY / 2) to get the center of the screen. The issue is the visualized ray cast fires toward a specific point in the world. However, this is only in the game’s place. In a separate environment, it works perfectly fine.

Here is the code running the calculation and visualizing how the bullet would travel.

local function visualizeRay(StartPosition, TargetPosition)
	print(StartPosition, TargetPosition)
	local distance = (StartPosition - TargetPosition).Magnitude
	if distance > 2024 then
		print("Distance is too large to visualize!", ` distance: {distance}`)

	local newPart ="Part")
	newPart.Parent = workspace
	newPart.Color =, 1, 0)
	newPart.Anchored = true

	newPart.Size =,0.5,distance)
	newPart.Material = Enum.Material.Neon

	local Center = (StartPosition + TargetPosition) / 2
	newPart.CFrame =, StartPosition)
	newPart.CanCollide = false
	newPart.Name = "Ray Visualization"

local function createRay(actionName, inputState, inputObject)
	if inputState ~= Enum.UserInputState.Begin then
	local viewportSize = workspace.CurrentCamera.ViewportSize
	local x = viewportSize.X / 2
	local y = viewportSize.Y / 2

	local centerScreenUnit = workspace.CurrentCamera:ScreenPointToRay(x, y)
	local startPosition = centerScreenUnit.Origin
	local targetPosition = centerScreenUnit.Direction * 500
	visualizeRay(startPosition, targetPosition)

local contextActionService = game:GetService("ContextActionService")
contextActionService:BindAction("VisualizeRay", createRay, true, Enum.UserInputType.MouseButton1)

Here is a video showcasing the same script in two different places giving two different outcomes. I’ve looked through the game’s code as well and nothing else interacts with the camera.

Video link: Raycasting Issue - YouTube

Is this an engine bug?
I don’t see how a math equations output is different if calculated in a different place.

Note: the script is only to help me make sure the screen calculation is right, this is not currently the gun system.