Answered by
5 years ago Edited 5 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:
01 | local player = game.Players.LocalPlayer |
02 | local char = player.Character or player.CharacterAdded:Wait() |
03 | player.CharacterAdded:Connect( function () char = player.Character end ) |
06 | if char:findFirstChild( "HumanoidRootPart" ) then |
07 | local origin = char.HumanoidRootPart.Position |
08 | local direction = char.HumanoidRootPart.CFrame.UpVector*- 1 |
09 | local ray = Ray.new(origin,direction* 10 ) |
10 | local ignoreList = { char } |
11 | local part = workspace:FindPartOnRayWithIgnoreList(ray,ignoreList) |
13 | local savedcolor = part.Color |
14 | part.BrickColor = BrickColor.Red() |
16 | part.Color = savedcolor |
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.