Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Creating a Part and Moving It to a Mouse Position?

I'm trying to make that if you click R it creates a part. I have no errors and it creates a part but it doesn't position it right. When I click R when my mouse is in another direction it makes the position different but it doesn't work like always :P

Local Script (Inside StarterGui):

local UIS = game:GetService("UserInputService")
local target = game.Players.LocalPlayer:GetMouse().Hit

function onKeyPress(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.R then
		local Part = Instance.new("Part", workspace)
		Part.Size = Vector3.new(4, 1, 2)
		Part.Anchored = true
		
		local x = target.X
		local y = target.Y
		local z = target.Z
		
		Part.Position = Vector3.new(x, y, z)
	end
end
 
UIS.InputBegan:Connect(onKeyPress)

I would really appreciate it if you will help me with my problem, Plus I'll accept your answer if it worked.

Thanks, MajinBluee

1 answer

✓ Accepted answer

Here you go:

local UIS = game:GetService("UserInputService")
local mouse = game.Players.LocalPlayer:GetMouse()

function onKeyPress(inputObject, gameProcessedEvent)
    if inputObject.KeyCode == Enum.KeyCode.R then
        local Part = Instance.new("Part")
        Part.Size = Vector3.new(4, 1, 2)
        Part.Anchored = true
        Part.Position = mouse.Hit.p
		Part.Parent = workspace
    end
end

UIS.InputBegan:Connect(onKeyPress)

You have to get the mouse first then inside the function use the .Hit or else the mouse's position won't update. .p is just the 3D position of where the mouse is pointing, not sure how to explain that. Also, always parent the part after you configure the properties of it, more lag-efficient.

2 comments

0

Thanks bruv.

0

np <3

This discussion is preserved as it was. New answers, comments, and votes are closed.