I want to make a tool that spawns a model at the player's mouse, here is my code if you want it
Localscript
1 | local player = game.Players.LocalPlayer |
2 | local RS = game:GetService( "ReplicatedStorage" ) |
3 | local Mesa = RS.Towers.Mesa |
4 | local Mouse = player:GetMouse() |
5 |
6 | script.Parent.Activated:Connect( function () |
7 | script.Parent.SpawnTower:FireServer(Mouse) |
8 | end ) |
ServerScript
1 | local RS = game:GetService( "ReplicatedStorage" ) |
2 | local Mesa = RS.Towers.Mesa |
3 |
4 | script.Parent.SpawnTower.OnServerEvent:Connect( function (Mouse) |
5 | local newtower = Mesa:Clone() |
6 | newtower.Parent = game.Workspace |
7 | newtower:MoveTo(Mouse.Position) |
8 | newtower.Name = "Mesa Tower" |
9 | end ) |
Instead of spawning at the player's mouse, it just spawns the model where it originally was. How fix?
Fix: localscript
1 | local player = game.Players.LocalPlayer |
2 | local RS = game:GetService( "ReplicatedStorage" ) |
3 | local Mesa = RS.Towers.Mesa |
4 | local Mouse = player:GetMouse() |
5 |
6 | script.Parent.Activated:Connect( function () |
7 | local Mousepos = Mouse.Hit.p --I need to get the mouse position right before firing the event |
8 | script.Parent.SpawnTower:FireServer(Mousepos) --Send the mouse pos to the server |
9 | end ) |
ServerScript
01 | local RS = game:GetService( "ReplicatedStorage" ) |
02 | local Mesa = RS.Towers.Mesa |
03 | local tool = script.Parent |
04 | local player = tool.Parent.Parent |
05 |
06 | script.Parent.SpawnTower.OnServerEvent:Connect( function (player, Mouse) -- Player is the first arguement always when firing from local |
07 | local newtower = Mesa:Clone() |
08 | newtower.Parent = game.Workspace |
09 | newtower:MoveTo(Mouse) --We already have the mouse pos so move to mouse |
10 | newtower.Name = "Mesa Tower" |
11 | end ) |
Mouse.Position returns a UDim2
value (I assume, it might be Vector2
) so you'll need a lot more code than that, here is an example of a UDim2
value:
1 | local pos = UDim 2. new(xoffset, 0 ,yoffset, 0 ) |
Here is an example of a Vector3
value:
1 | local pos = Vector 3. new(x, y, z) |
Here is an example of a Vector2
value:
1 | local pos = Vector 2. new(x,y) |
Accept this answer if it helped! (No one on here is giving you code, you're here to learn, not be spoon-fed the answer)
Mouse.Position
does not return a Vector3
value, so you are going to need to look at this from another angle.
When trying to find the position where the mouse clicked in the games 3D space, we use one of the mouse's properties called Hit
.
Here is an example of the Hit
property:
1 | local position = mouse.Hit.p |
I hoped this helps, commend below if you need further assistance.