So as you know in order to convert the mouse’s coordinates from screenspace to worldspace you must raycast towards the mouse position.
There are a variety of ways roblox allows us to do this, but all of them seem to involve some deprecated system.
Mouse.Hit – Mouse class deprecated
Mouse.UnitRay – Mouse class deprecated, Ray object
ViewportPointToRay along with its brother ScreenPointToRay both involve creating a useless Ray object, which also may be deprecated
After those 3 options though, roblox doesnt give you any up to date way to convert from the mouse’s screenspace coordinates, to a worldspace coordinate. So I ended up having to make my own…
local function RaycastX(rayParams, distance)
assert(typeof(rayParams) == "RaycastParams")
assert(type(distance) == "number")
local viewportSize = camera.ViewportSize
local theta = (camera.FieldOfView / 2) * (math.pi / 180)
local ar = viewportSize.X / viewportSize.Y
local l = -camera.NearPlaneZ * math.tan(theta)
local halfSize = viewportSize / 2
local mousepos = UserInputService:GetMouseLocation()
mousepos = (mousepos - halfSize) / halfSize
mousepos = Vector2.new( mousepos.X * ar, mousepos.Y )
local front = Vector3.FromAxis(Enum.Axis.Z) * camera.NearPlaneZ
local right = Vector3.FromAxis(Enum.Axis.X) * mousepos.x * l
local up = Vector3.FromAxis(Enum.Axis.Y) * -mousepos.y * l
local localized = camera.CFrame:VectorToWorldSpace(front + right + up)
local localizedUnit = localized.Unit
return workspace:Raycast(camera.CFrame.Position, localizedUnit * distance, rayParams)
end
While this method works, I was just wondering if this is a complete waste of time and I should just use either the Mouse class or use either one of the ViewportPointToRay or ScreenPointToRay, just because I don’t know if my method could be potentially slower than those ways, or just overall more code that takes a more convoluted route in order to do something that can be achieved the methods above much easier.
I don’t know, what are your opinions?