Detecting if a Player is near Part(s) and Terrain

Hi Devs,

To begin with I am using Gravity Controller, which allows the player to walk on the sides of parts and terrains. It is open sourced if you would like to look at the RayCasting included within it

I am certain that it already has what I am looking for built in by using RayCasting, but I am unsure of read the code and figure out exactly what I am looking for.

Basically, I am looking for a way to detect if the player is within 1 stud of a part or terrain. However, I am unsure of how I would do this, so if anyone would be able to get me moving in the right direction, please let me know.

there are a few ways id recommend you look into “Region3” (it effectively creates a hit box around the part you want to detect). size of region and location of region are of your choosing, then you loop through the parts in the region, you can do this by creating a whitelsit (things to look out for) or a black list parts to ignore (these are built in functions of “Region3”

or you could loop create a loop that gives the magnitude (the total length) between your character and the block your trying to detect heres an example

while true do 
	local MagnitudeBetweenPlayerAndPart = (Part, Player.Part).Magnitude -- gives distance between "part" and a part of the player
	if MagnitudeBetweenPlayerAndPart < 1 then
		print("the character is less than 1 stud away from the block ")
	end
end

if theres anything you dont understand feel free to ask and ill answer to the best of my ability!

2 Likes

I have never heard of Region3, but I am not sure if that or a magnitude loop will work, since I will need something to that detects every part in the game, as well as terrain.

If I am wrong about that then please let me know and I will give it a try.

yeah my bad i was actually thinking about this a bit afterwards and im surprised this wasnt the first thing that came to mind.

if you do a foot.touched event then it will detect everything your walking on, you can then debounce it so that it sets the gravity for the part you are on then ignore it while its the center of gravity

e.g:

--just something like this
local CenterOfGravityPart
foot.touched:Connect(function(hit)
	if hit.Name ~= CenterOfGravityPart then
		hit = --make this part the Center Of Gravity
		CenterOfGravityPart = hit.Name
	end
end)
1 Like