Code performance

What can you say about this code that checks if the player is inside a zone? It seems to me that it’s more performant than other methods

Also, this method can get the entry point.

local RunService = game:GetService("RunService")

local Players = game:GetService("Players")
local plr = Players.LocalPlayer

local char = plr.Character or plr.CharacterAdded:Wait()
local hum_root = char.HumanoidRootPart

local zone = -- путь до зоны
local diogonal_of_zone = zone.Size:Dot(zone.Size)

local touch_status = false;

local function on_touch()
  -- your code
end

local function on_touch_ended()
  -- your code
end

local min = math.min
local sqrt = math.sqrt
local dot = vector.dot

RunService.HeartBeat:Connect(function()
  local char_pos = hum_root.Position
  local dir = zone.CFrame:PointToObjectSpace(char_pos).Unit:Abs();
  
  local ab = zone.Position - char_pos
  local ab_scalar = dot(ab, ab)
  
  if ab_scalar > diogonal_of_zone/2 then return end
  
  local in_lenght = min(
    zone.Size.X / dir.X,
    zone.Size.Y / dir.Y,
    zone.Size.Z / dir.Z
  )
  
  if sqrt(ab_scalar) <= in_lenght/2 then
    if touch_status then return end
    touch_status = true; on_touch()
    
  elseif touch_status then
    touch_status = false
    on_touch_ended()
    
  end
end)
1 Like

GetPartBoundsInBox is pretty optimized man. Id recommend using that instead of this. While programming it yourself might seem like itll run faster since you only have what you need but thats not the case.

Lua is a high level language built off of C meaning its slower. To remedy this, certain built in functions are written in C and called by lua so that performance isnt that bad. GetPartBoundsInBox is written in C and can run thoudands of times in a 10th of a second.

Lastly, do you really need to run this check every frame? Can a player reasonablly be in the zome on one frame then completely out the next?

1 Like