Jump to content

getDistanceBetweenPoints3D?


Sasu

Recommended Posts

How can I make to find the nearest coordinates to my player?

Ex: I have this table

coordinatesTable = { 
{x, y, z}, 
{x, y, z} 
} 

And I need the nearest coodinates to my player. How can I do? I think getDistanceBetweenPoints3D but I dont know how to do.

Link to comment
local coordinatesTable =  
    { 
        { x, y, z }, 
        { x, y, z } 
    } 
  
function sortCoordiantesByDistance ( x, y ) 
    local coordinates = { } 
    for _, pos in ipairs ( coordinatesTable ) do 
        table.insert ( 
            coordinates, 
            { 
                pos [ 1 ], 
                pos [ 2 ], 
                pos [ 3 ], 
                getDistanceBetweenPoints2D ( x, y, pos [ 1 ], pos [ 2 ] ) 
            } 
        ) 
    end 
  
    table.sort ( 
        coordinates, 
        function ( a, b ) 
            return ( tonumber ( a [ 4 ] ) or 0 ) < ( tonumber ( b [ 4 ] ) or 0 ) 
        end 
    ) 
  
    return coordinates 
end 

Example:

addCommandHandler ( "sort", 
    function ( thePlayer ) 
        local x, y = getElementPosition ( thePlayer ) 
        local coords = sortCoordiantesByDistance ( x, y ) 
        -- do something 
    end 
) 

Link to comment
  
-- this function return the x,y,z coordinates of the nearest point.  
function findNearestCoordinates (x, y, z) 
    local nearestPoint = coordinatesTable [1]; 
    local minSqrDist = (nearestPoint[1] - x)^2 + (nearestPoint[2] - y)^2 + (nearestPoint[3] - z)^2; 
  
    for i=2,#coordinatesTable,1  do 
        local j = coordinatesTable [i]; 
        local d = (j[1] - x)^2 + (j[2]-y)^2 + (j[3]-z)^2; 
        if d < minSqrDist then 
            d = minSqrDist; 
            nearestPoint = j; 
        end; 
    end; 
  
    return unpack (nearestPoint); 
end; 
  
  

example ->

  
local pX, pY, pZ = getElementPosition (player); 
local sX, sY, sZ = findNearestCoordinates (pX, pY,pZ); 
-- nearest point to player is sX, sY, sZ 
  

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...