Any methods to check distances between Character and multiple Parts?

I’m working on a project which requires that a lot of objects (such as trees and basic buildings) be in the same place as a Player, however loading the sheer amount of parts I have planned seems too redundant, and will probably cause a lot of lag.

In short, I’m looking for a way to check the distances between certain points where detailed structures would be loaded.

So far I’ve looked into Vector3 magnitude, but this would require constantly checking this distance between every potential object and the character.
I also had the idea of using GetDistanceFromCharacter() but this falls short due to the same problem.

Is there a simple solution for this? I feel like I’m missing something

If you are doing some sort of rendering system, you could always use StreamingEnabled. Otherwise, I would have one part from each model/object/building/whatever that you want to check the distances between in a table, then iterate through that table (something like below):

local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local LocalPlayer = Players.LocalPlayer
local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
local HumanoidRootPart = Character.PrimaryPart

local RenderMagnitude = 100 --how close parts need to be
local UpdateMagnitude = 15 --how far the player needs to move before the table of parts is updated

local instances = {}
local previous

RunService.Heartbeat:Connect(function()
  if previous and (HumanoidRootPart.Position - previous).Magnitude < UpdateMagnitude then
    return
  end

  local inRange = {}

  for i, v in instances do
    if (HumanoidRootPart.Position - v.Position).Magnitude < RenderMagnitude then
      table.insert(inRange,v)
    end
  end

  previous = HumanoidRootPart.Position

  --do whatever with the table of in range parts
end)

I don’t know if that is helpful or not, depending on your use case, but hopefully it is. By using a table with only one part per model/whatever you are greatly decreasing the number of instances you are iterating through, and then by only updating what parts are in range when the player has moved a certain distance, you aren’t doing useless calculations.

1 Like

Thanks, I’ll look more into Content Streaming, but it seems like calling a few parts through a table or list would work better for what I’m trying to do

1 Like

Try using @Quenty’s excellent OctTree module. It’s fast and efficient for breaking down parts into a search radius. it can be coupled with the camera so stuff behind the player are not included in the search.

It’s included in @boatbomber’s excellent WindShake demo here. You should be able to glean it’s usage from the uncopylocked places here:

Wind Shake: High performance wind effect for leaves and foliage - Resources / Community Resources - Developer Forum | Roblox

1 Like