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

How would I check if there is a part at a certain position?

Asked by
tjtorin 172
4 years ago
Edited 4 years ago

Assume that the player just mined (destroyed) a block. I would want to spawn a block right under the block they just mined but only if there is no block beneath it.What would be the best method to check if their is a part at a certain position such as the part the player just mined subtracted by a vector?

1 answer

Log in to vote
2
Answered by
Dfzoz 489 Moderation Voter
4 years ago
Edited 4 years ago

You can use raycasting and check if a part collides with it by using workspace:FindPartOnRay(ray), which returns the first part that collides with that ray.

To create a ray, use Ray.new(origin vector3, direction vector3).

If you want to filter parts on the raycast, you can use workspace:FindPartOnRayWithWhitelist(ray,array) or workspace:FindPartOnRayWithIgnoreList(ray,array).

This is an example of raycasting, put it on a LocalScript. The code raychecks every second if there is a part beneath the player and if it does, it changes its color to red for one second:

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
player.CharacterAdded:Connect(function() char = player.Character end)

while true do
    if char:findFirstChild("HumanoidRootPart") then
        local origin = char.HumanoidRootPart.Position
        local direction = char.HumanoidRootPart.CFrame.UpVector*-1
        local ray = Ray.new(origin,direction*10)
        local ignoreList = {char} --ray wont collide with your own character anymore
        local part = workspace:FindPartOnRayWithIgnoreList(ray,ignoreList)
        if part then
            local savedcolor = part.Color
            part.BrickColor = BrickColor.Red()
            wait(1)
            part.Color = savedcolor
        end
    end
    wait(1)
end

You can also use region3 to check with workspace:FindPartsInRegion3(). This returns all parts on a region3, and you can also filter it with a whitelist or ignorelist variant of the function.

Ad

Answer this question