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

Not completely understanding mouse.hit?

Hey! So I'm trying to make this script where when the player clicks anywhere a part will spawn where ever the mouse was clicked, the problem is that the part spawns but not at the position of the mouse. Here's the code:

Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()
local PosX,PosY,PosZ = Mouse.Hit.X,Mouse.Hit.Y,Mouse.Hit.Z

Mouse.Button1Down:connect(function()
	local MousePos = Mouse.Hit.p
	if Mouse.Target ~= nil then
		local Part = Instance.new("Part", game.Workspace)
		Part.Position = Vector3.new(PosX,PosY,PosZ)
	end
end)

I'm completely new to mouse manipulation and i'm trying to get better at it, if someone could leave an explanation on why this is happening that would be great!

2 answers

✓ Accepted answer

Hello there! Mouse.Hit.X, etc doesn't work as you would expect, It wouldn't spawn it in the actual position of the mouse. Just at some point very very far away. You should use Mouse.X or Mouse.Y, (Mouse.Z is not a thing). However, I would just use mouse.Hit. For mouse.hit you need to change it to CFrame

Player = game.Players.LocalPlayer
Mouse = Player:GetMouse()
local PosX = Mouse.Hit.X
local PosY = Mouse.Hit.Y
local PosZ = Mouse.Hit.Z

Mouse.Button1Down:connect(function()
    local MousePos = Mouse.Hit.p
    if Mouse.Target ~= nil then
        local Part = Instance.new("Part")
		Part.Parent = workspace
        Part.CFrame = Mouse.Hit
    end
end)

If this was helpful please accept, otherwise tell me so

Well even though im a noob at coding, i am fimular with some of your code, maybe you should make the variables for the Mouse.Hit.X,Mouse.Hit.Y,Mouse.Hit.Z separate and in one variable. Hoped this helped.

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