How does one move a part with the player's mouse? For example, when you click and hold the part, you can drag the part as it follows the mouse until your release it
What you're looking for is the PlayerMouse
object. This object is obtained by calling the GetMouse
method on a local player
, which obviously means it will only work in a local script
.
Mouse events?
There are certain events that can be established through the mouse object, all in which are based on user input. Here's a list:
Button1Up - Left click up
Button1Down - Left click down
Button2Up - Right click up
Button2Down - Right click down
Idle - Mouse isn't moving
Move - When the mouse moves
WheelBackward - Fired when the mouse scroll wheel is pushed forward
WheelForward - Fired when the mouse scroll wheel is pushed backward
What you need?
For you question, we only need to focus on Button1Up
and Button1Down
. Here are the necessary components you'll need to know for a program like this:
Button1Up Button1Down Mouse.Target - Property of PlayerMouse. What the mouse is hovering over. Mouse.Hit - Property of PlayerMouse. The CFrame of where the mouse is pointing Mouse.TargetFilter - Property of PlayerMouse. Mouse.Hit will ignore instances set to this.
Program composition?
-- Inside a local script local Player = game:GetService'Players'.LocalPlayer local Mouse = Player:GetMouse() -- Get the mouse local Dragging = false local Part = Instance.new("Part",workspace) Part.Anchored = true Mouse.TargetFilter = Part -- Ignore the part on the mouse detection -- When the mouse moves, and Dragging is true, then... Mouse.Move:connect(function() if Dragging then Part.CFrame = Mouse.Hit end end) -- When the player's mouse is clicked down... Mouse.Button1Down:connect(function() Dragging = true end) -- When the left click is realest, then... Mouse.Button1Up:connect(function() Dragging = false end)
Hope this helped. If you have any questions, let me know.