Skip to content

Distance calculation and GetClosestEnemy seems wrong #2

Description

@nutshoekey

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions