I am making a simple script that makes a part follow the mouse when the mouse moves, but for some reason it just doesn’t work. I have gotten the game to get the mouse, but the part just doesn’t follow the mouse and I don’t know why. This is all on a LocalScript, by the way.
local Part = game.Workspace.Part
local Mouse = game:GetService('Players').LocalPlayer:GetMouse()
local Mousepos = Mouse.Hit
while true do
Part.CFrame = Mousepos
wait()
end
mousepos is more or less a “copy” of mouse.hit. Move it to the inside of the loop.
Also, you will want to add Part to the Mouse’s TargetFilter so that it doesn’t spaz towards the camera.
local Part = game.Workspace.Part
local Mouse = game:GetService('Players').LocalPlayer:GetMouse()
while true do
local Mousepos = Mouse.Hit
Part.CFrame = Mousepos
wait()
end
He is assigning to a CFrame, so he needs to use Mouse.Hit. The caveat is that it will keep the bizzare rotation of the mouse.
Adding onto this I recommend using RenderStepped instead of a while loop due to it running every frame as well making sure to add a check if mousepos is nil as if the mouse isn’t hitting anything it will return nil and break.
Oh, I just realized that StarterPlayerScripts also works with LocalScript? Thank you, because I’ve got some trouble with my LocalHandles, alot of them been placed inside StarterGui so it’s pretty messy.
local Part = game.Workspace.Part
local Mouse = game:GetService('Players').LocalPlayer:GetMouse()
while true do
Mouse.TargetFilter = Part
local Mousepos = Mouse.Hit.p
Part.CFrame = CFrame.new(Mousepos)
wait()
end
You can add a ‘p’ after Mouse.hit to get the position in vector3.
Mouse.Hit is going to return the position but will also return the rotation of the mouse, you might want to use your own rotation script.
Also add a target filter so the Mouse can ignore the Part, or the mouse.Hit.p will keep returning the position of the Part, not the position of where you point the mouse in the workspace.
Use Jared’s solution If you want to keep the bizzare rotation of the mouse.
local RunService = game:GetService("RunService") -- Services
local Players = game:GetService("Players")
local player = Players.LocalPlayer -- Player stuff
local mouse = player:GetMouse()
local part = workspace:WaitForChild("Part") -- Part stuff
mouse.TargetFilter = part -- So mouse doesn't "hit" the part
RunService.Heartbeat:Connect(function() -- Heatbeat runs after every critical calculation
if mouse.Target then -- Part doesn't go into space
part:PivotTo(CFrame.new(mouse.Hit.Position)) -- PivotTo works with parts and models
end
end)