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

How do I move a Model to the Player's Mouse?

Asked by 6 years ago

So i'm trying to make a Model placement system, But I can't seem to figure out how to move a Model correctly..

1 answer

Log in to vote
1
Answered by
DanzLua 2879 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

I'm going to make it so that you can hold down on a model and move it around while the mouse is down on it.

Lets use the :SetPrimaryPartCFrame() function to move the models

First make sure your model has a PrimaryPart set

For the Button1Down event we will check to see if 1) the mouse.target isnt nil 2) the parent of the mouse.target is a model AND that its PRIMARY PART IS SET and 3) mouse.target.parent.parent == workspace . Then setting the target as the mouse.target's parent. adding that model to the targetfilter, and setting down to true

mouse.Button1Down:connect(function()
    if mouse.Target ~= nil then
        if mouse.Target.Parent:IsA("Model") and mouse.Target.Parent.PrimaryPart~=nil and mouse.target.parent.parent==workspace then
            target = mouse.Target.Parent
            mouse.TargetFilter=target
            down = true
        end
    end
end)

For the move event we will check if target isnt nil and down == true. then we will use :SetPrimaryPartCFrame() to move the model

mouse.Move:connect(function()
    if down == true then
        if target ~= nil then
            target:SetPrimaryPartCFrame(CFrame.new(mouse.Hit.p))
        end
    end
end)

Remember we can rotate the model by adding *CFrame.Angles() at the end of CFrame.new()

finally for the button1up event, we will set down to false, target to nill, and clear out the targetfilter

mouse.Button1Up:connect(function()
    down = false
    target = nil
    mouse.TargetFilter = nil
end)

Final form

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local target = nil
local down = nil
local plr = game.Players.LocalPlayer

mouse.Button1Down:connect(function()
    if mouse.Target ~= nil then
        if mouse.Target.Parent:IsA("Model") and mouse.Target.Parent.PrimaryPart~=nil and mouse.target.parent.parent==workspace then
            target = mouse.Target.Parent
            mouse.TargetFilter=target
            down = true
        end
    end
end)

mouse.Move:connect(function()
    if down == true then
        if target ~= nil then
            target:SetPrimaryPartCFrame(CFrame.new(mouse.Hit.p))
        end
    end
end)

mouse.Button1Up:connect(function()
    down = false
    target = nil
    mouse.TargetFilter = nil
end)

Make sure this is in a localscript

Ad

Answer this question