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

How Do I Find The Clicked Parts Name And Distance From Torso?

local Player = game.Players.LocalPlayer local Mouse = Player:GetMouse()

Mouse.KeyDown:connect(function(key)

Mouse.Button1Down:connect(function()

	local Char = Player.Character
	local Origin = Char:FindFirstChild("Torso").Position
	local ray = Ray.new(Origin * 500)
	local part, hitPosition = workspace:FindPartOnRay(ray, Char)
	if part.Parent == "Grid" then
		print(part.Name)
	end
end)

end)

I can't seem to get through this. I've basically set up a grid of 36 squares, put them in a Model named "Grid" I want to create a script that when the player clicks, if it's one of the grid squares they clicked, print the name of the grid square.

2 comments

0

Line 7 try part.Parent.Name == "Grid".

0

Players.Ruves.Backpack.LocalScript:17: attempt to index local 'part' (a nil value) 12:26:43.790 - Stack Begin 12:26:43.791 - Script 'Players.Ruves.Backpack.LocalScript', Line 17 12:26:43.791 - Stack End

1 answer

✓ Accepted answer

Your error occured in the first place because you did not compare the model's name with "Grid" and the way you create your ray is wrong. Ray.new() takes two arguments, the origin and the direction of the ray. You did not set the direction of the ray.

You also do not need to put Mouse.Button1Down inside a Mouse.KeyDown.

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

local Char = Player.Character
local Origin = Char:FindFirstChild("Torso")

Mouse.Button1Down:Connect(function()
	--(Mouse.Hit.p - Origin.Position) is how to calculate the direction Vector3, make it a unit vector then multiply by 500.
	local ray = Ray.new(Origin.Position, (Mouse.Hit.p - Origin.Position).unit * 500)
	local part, hitPosition = workspace:FindPartOnRay(ray, Char)
	--Check if part exists.
	if part then
		if part.Parent.Name == "Grid" then
		    print(part.Name)
		end
	end
end)

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