local player = game.Players.LocalPlayer local mouse = player:GetMouse() mouse.Button1Up:Connect(function() Down = false end) mouse.Button1Down:Connect(function() local part = Instance.new("Part", workspace) local BP = Instance.new("BodyPosition", part) BP.MaxForce = Vector3.new(math.huge, math.huge, math.huge) Down = true while Down == true do wait() BP.Position = mouse.Hit.Position - mouse.Hit.Position + 10 end end)
What I am trying to do is you pick up the part, it moves to the mouse position, however, it will always be 10 studs away from you, but will still folow the mouse. Help`?
local player = game.Players.LocalPlayer local Character = player.Character or player.CharacterAdded:Wait() local humanoidrootpart = Character:WaitForChild("HumanoidRootPart") local mouse = player:GetMouse() local OFFSET = 10 mouse.Button1Up:Connect(function() Down = false end) mouse.Button1Down:Connect(function() local part = Instance.new("Part") part.Parent = workspace local BP = Instance.new("BodyPosition") BP.Parent = part BP.MaxForce = Vector3.new(math.huge, math.huge, math.huge) Down = true while Down == true do wait() local Direction = (mouse.Hit.p - humanoidrootpart.Position).Unit BP.Position = humanoidrootpart.Position + (Direction * OFFSET) end end)
Let me explain the changes. Firstly, you want to create a unit length vector that points out from your character to your mouse location. That's how you can make create a position relative to your character. Secondly , if you want your part to point out 10 studs away from your character, you want to make a offset. The position of the part should be on your character (I prefer HumanoidRootPart) and then you add your offset.
Also, I want to point out that the reason that I chose to type:
local part = Instance.new("Part") part.Parent = workspace
instead of:
local part = Instance.new("Part", workspace)
Is because it causes performance issues. You can read more about it here. Just a tip.
This is a very simple vector problem, which can be solved as follows:
First get the target position (mouse.Hit.p)
Then you calculate the unit vector from the humanoid root part to the target position
Multiply the unit vector by the distance you want the part to be
And finally, BP position = humanoid root part position + (direction * distance)
Here is the modified code:
local player = game.Players.LocalPlayer local char = player.Character or player.CharacterAdded:wait() local hrp = char.HumanoidRootPart local mouse = player:GetMouse() mouse.Button1Up:Connect(function() Down = false end) mouse.Button1Down:Connect(function() local part = Instance.new("Part", workspace) local BP = Instance.new("BodyPosition", part) BP.MaxForce = Vector3.new(math.huge, math.huge, math.huge) Down = true while Down == true do wait() local targetPos = mouse.Hit.p local direction = (targetPos - hrp.CFrame.p).Unit BP.Positon = hrp.CFrame.p + direction * 10 end end)