Forum

> > CS2D > Scripts > How to get the closest player ID?
Forums overviewCS2D overview Scripts overviewLog in to reply

English How to get the closest player ID?

2 replies
To the start Previous 1 Next To the start

old How to get the closest player ID?

Mami Tomoe
User Off Offline

Quote
Hello, I would like to be able to find the closest player to the given ID.
For example using a function like this:

closestTarget(1)

Will return the ID of the player closest to the player with the ID of 1.

Thanks in advance.

old Re: How to get the closest player ID?

TrialAndError
User Off Offline

Quote
Check the distance between all living players and the id, get the smallest distance and return the ID of the player. It will return nil if there are no living players.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function distance(x1, y1, x2, y2)
    return (math.sqrt((x2-x1)^2 + (y2-y1)^2))
end

function closestTarget(id)
    local closest;
    for _, target in ipairs(player(0,"tableliving")) do
        if id ~= target then
            local d = distance(player(id, "x"), player(id, "y"), player(target, "x"), player(target, "y"))
            if closest == nil or d < closest.dist then
                closest = {id = target, dist = d}
            end
        end
    end
    return closest ~= nil and closest.id or nil
end
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview