-
Notifications
You must be signed in to change notification settings - Fork 6
Distance calculation and GetClosestEnemy seems wrong #2
Copy link
Copy link
Open
Description
Your current GetClosestEnemy returns too early, it returns the first player in the list, and the distance calculation can go negative
local function GetClosestEnemy()
local LocalOrigin = { EntityGetOrigin(EntityGetLocalPlayer()) }
local NearestDistance, NearestEntity
local Players = EntityGetPlayers(true)
if #Players == 0 then
return
end
for i=1, #Players do
local Player = Players[i]
local TargetOrigin = { EntityGetOrigin(Player) }
local DistanceToTarget = MathHelpers.DistanceTo(LocalOrigin, TargetOrigin)
if NearestDistance == nil or DistanceToTarget < NearestDistance then
NearestEntity = Player
NearestDistance = DistanceToTarget
end
if NearestDistance and NearestEntity then
return NearestEntity, MathHelpers.UnitsToFeet(NearestDistance)
end
end
return nil, 0
end
Here is the fixed one
local MathHelpers = {
DistanceTo = function(from, to)
local from = { x = from[1], y = from[2], z = from[3] }
local to = { x = to[1], y = to[2], z = to[3] }
local subtraction = { x = to.x - from.x, y = to.y - from.y, z = to.z - from.z }
local result = MathSqrt((subtraction.x * subtraction.x) + (subtraction.y * subtraction.y))
return result
end,
UnitsToFeet = function(units)
local Meters = MathFloor((units * 0.0254))
return MathFloor((Meters * 3.281))
end,
OnGround = function(entindex)
return (BitBand(EntityGetProp(entindex, "m_fFlags"), 1) ~= 0)
end
}
local function GetClosestEnemy()
local LocalOrigin = { EntityGetOrigin(EntityGetLocalPlayer()) }
local NearestDistance, NearestEntity
local Players = EntityGetPlayers(true)
if #Players == 0 then
return
end
for i=1, #Players do
local Player = Players[i]
local TargetOrigin = { EntityGetOrigin(Player) }
local DistanceToTarget = MathHelpers.DistanceTo(LocalOrigin, TargetOrigin)
if NearestDistance == nil or DistanceToTarget < NearestDistance then
NearestEntity = Player
NearestDistance = DistanceToTarget
end
end
if NearestDistance and NearestEntity then
return NearestEntity, MathHelpers.UnitsToFeet(NearestDistance)
else
return nil, 0
end
end
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels