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

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

Asked by
Ruves 21
6 years ago

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.

0
Line 7 try part.Parent.Name == "Grid". Rheines 661 — 6y
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 Ruves 21 — 6y

1 answer

Log in to vote
0
Answered by
Rheines 661 Moderation Voter
6 years ago
Edited 6 years ago

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)
Ad

Answer this question