Ok so this is the basic idea. The center of the screen would be (0, 0)
, the top right corner is (1, 1)
, and the bottom left would be (-1, -1)
.
You can use the linear interpolation formula to figure out what the coordinate should be for any position on the screen. This is the formula:
goal = start + alpha*(finish - start)
But we need to find alpha
, not goal. We know what everything else should be. goal
is the position of the mouse, start
is always going to be (0, 0)
since that’s where the screen starts, and finish
is just the screen size.
To get alpha
, we can do some simple algebra:
goal - start = alpha*(finish - start) --move start to the other side
(goal - start)/(finish - start) = alpha*(finish - start)/(finish - start) --divide both sides by (finish - start)
alpha = (goal - start)/(finish - start)
Since start
is always going to be zero, we can actually leave it out of the equation:
alpha = goal / finish
And now we just need to plug in the variables. We will need to use this formula for each dimension.
local goal = UserInputService:GetMouseLocation()
local finish = workspace.CurrentCamera.ViewportSize
local x_alpha = goal.X / finish.X
local y_alpha = goal.Y / finish.Y
But a few more things, alpha
is in the range [0, 1]
. We need to convert to [-1, 1]
.
--first turn it into [-0.5, 0.5] by shifting it down, then multiply by two to turn it into [-1, 1]
local x_alpha = ((goal.X / finish.X) - 0.5) * 2
local y_alpha = ((goal.Y / finish.Y) - 0.5) * 2
In addition, the Y value is flipped since 0
is the top left when it should be at the bottom. We have to invert it by doing 1 - alpha
.
local y_alpha = (1 - (goal.Y / finish.Y) - 0.5) * 2
--this simplifies to
local y_alpha = (0.5 - goal.Y / finish.Y) * 2
Now we have the actual value.
local lean = Vector2.new(x_alpha, y_alpha)