Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can I Constantly Get the Mouse Location of Any Player?

Asked by 4 years ago

I need my game to be able to retrieve the Mouse.Hit position of each client every second or so. I have the following in a local script within the StarterPlayerScripts:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MouseTargetEvent = ReplicatedStorage:WaitForChild("MouseTargetEvent")

local mouse = game:GetService("Players").LocalPlayer:GetMouse()

while wait(.1) do
    if mouse.Target ~= nil then
        curr_target = mouse.Target.Name
    end
    MouseTargetEvent:FireServer(mouse.Hit.p, curr_target)
end

The global server event is located in ServerScriptService as:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MouseTargetEvent = Instance.new("RemoteEvent", ReplicatedStorage)
MouseTargetEvent.Name = "MouseTargetEvent"

local function MouseTargetChangedFunction(player, mouse_pos, mouse_target)
    --print(player.Name, "has changed their mouse target")
    game.ReplicatedStorage.MousePosition.Value = mouse_pos
    --print(game.ReplicatedStorage.MousePosition.Value)
    if mouse_target ~= nil then -- handles cases where the mouse is on the sky (aka nothing)
        game.ReplicatedStorage.MouseTarget.Value = mouse_target
        --print(game.ReplicatedStorage.MouseTarget.Value)
    end
end

MouseTargetEvent.OnServerEvent:Connect(MouseTargetChangedFunction)

For whatever reason (probably that the MousePosition is global for some reason), the mouse locations of all players in the server are calculated rather than just that of the client. How can I fix this, while still being able to use the client's mouse position in a global script?

1
Because there is only one MousePosition object. And each local script is firing the event and the last firer overwrites it. I think you meant to have multiple MousePositions. Also, calling wait in the conditional part of a while loop is not good practice. See here for more info: https://docs.google.com/document/d/1ieZ8OzXPiXe3R7rs_xWmYZOnhQevlagN0ZWwoj_zKP4/edit and you don't need to be firing User#24403 69 — 4y
0
the event that constant User#24403 69 — 4y

Answer this question