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}`)
return
end
local newPart = Instance.new("Part")
newPart.Parent = workspace
newPart.Color = Color3.new(0.94902, 1, 0)
newPart.Anchored = true
newPart.Size = Vector3.new(0.5,0.5,distance)
newPart.Material = Enum.Material.Neon
local Center = (StartPosition + TargetPosition) / 2
newPart.CFrame = CFrame.new(Center, StartPosition)
newPart.CanCollide = false
newPart.Name = "Ray Visualization"
end
local function createRay(actionName, inputState, inputObject)
if inputState ~= Enum.UserInputState.Begin then
return
end
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)
end
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.