I am currently creating a editing system like Fortnite.
I am using Mouse.Target to detect if the player is selecting a tile. This works fine, other than the fact that the mouse seems to not be centered as seen in the video below.
How could I center it correctly with a custom camera. (I have already tried RayCasting from the camera and it wasn’t centered.)
The Mouse instance isn’t supported by Roblox much. You should try using UserInputService and Camera methods.
You can convert the MouseLocation to a Ray, which you can then cast and detect the hit object.
Here’s an example:
local UserInputService = game:GetService("UserInputService")
local reach = 30
UserInputService.InputChanged:Connect(function(input, processed)
if not processed and input.UserInputState == Enum.UserInputType.MouseMovement then
local location = UserInputService:GetMouseLocation()
local ray = workspace.CurrentCamera:ViewportPointToRay(location.X, location.Y, 0)
local result = workspace:Raycast(ray.Origin, ray.Direction * reach)
if result and result.Instance then
-- do something
end
end
end)
You probably need some RaycastParams to stop it detecting the player.
local players = game:GetService("Players")
local player = players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local params = RaycastParams.new()
params.IgnoreWater = true
params.FilterDescendantsInstances = char:GetDescendants()
params.FilterType = Enum.RaycastFilterType.Exclude
--then, when casting the ray:
local result = workspace:Raycast(ray.Origin, ray.Direction * reach, params)
Tried it and it delivered the same outcome from when I was using Mouse.Target.
The problem is even though the cursor is shown the be in the center, it is not instead the mouse seems to be positioned somewhere to the left as you can see from the video.
Maybe instead of using the Mouse.Target, try just always casting from the centre of the screen. Size a GUI element to {1, 0}, {1, 0} and size it down. Then, position it to the middle of the screen. Take note of the decimal values in it’s Position property, and store them as a UDim2 value in your script. Then, you can use workspace.CurrentCamera:ScreenPointToRay(value.X.Scale, value.Y.Scale) and get the ray that way.
Just make a ScreenGui under StarterGui and drag it until it aligns with the middle of the screen. Copy the position of it. You can delete the GUI object afterwards.
Then, open up the LocalScript and put it in.
local pos = UDim2.new(xPosHere, 0, yPosHere, 0)
Then, when you want to use it, just do:
local ray = workspace.CurrentCamera:ScreenPointToRay(pos.X.Scale, pos.Y.Scale, 0)
local result = workspace:Raycast(ray.Origin, ray.Direction * rangeFactor, 0)
if result then
--the ray hit. Do stuff here.
end