Getting mouse position after clicking a part with a click detector

basically i have this hose when clicked will allow the player to place(click to place) the end of the hose where the mouse is in 3d space.

issue is, that server scripts cant get the players mouse. My last idea was after clicking it’ll put a local script in the player and have that get the mouse coordinate but that feels inefficient and over complicated

got other solutions to tis?

1 Like

Your assessment is correct— server scripts do not have access to client-specific objects like the player’s mouse. The common approach to solving this issue is indeed using a LocalScript to handle client-side actions, such as mouse clicks, and then communicating the necessary information back to the server.

Here’s a simplified and efficient approach to implement your hose placement feature using a LocalScript and a RemoteEvent:

The LocalScript would be responsible for detecting the player’s mouse click and sending the 3D world position to the server.

Create a RemoteEvent in ReplicatedStorage to handle the communication between the client and the server.

-- Local Script
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Assuming you have a RemoteEvent set up in ReplicatedStorage for this purpose
local placeHoseEvent = ReplicatedStorage:WaitForChild("PlaceHoseEvent")

local player = Players.LocalPlayer
local mouse = player:GetMouse()

-- Bind an action to the mouse click, e.g., when the player clicks the hose
mouse.Button1Down:Connect(function()
    -- Get the 3D position of the mouse hit
    local hitPosition = mouse.Hit.p
    -- Fire the RemoteEvent to send the position to the server
    placeHoseEvent:FireServer(hitPosition)
end)

The server Script reacts to the RemoteEvent being fired and places the hose end at the position provided by the client.

-- Server Script
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local placeHoseEvent = ReplicatedStorage:WaitForChild("PlaceHoseEvent")

-- Function to place the hose end
local function placeHose(player, position)
    -- Logic to place the hose end at the given position
    -- Make sure to include security checks to validate the position
end

-- Connect the RemoteEvent to the placeHose function
placeHoseEvent.OnServerEvent:Connect(placeHose)

2 Likes

You must detect the Click on the client. Then you can cast a ray on the client and send the hit result to the server.

1 Like