Let's say I have a player located at: X: 100, Y: 100, Z: 100
and I want to find which of the following points is the closest and get it's ID.:
ID: 1, X: 200; Y: 200; Z: 100,
ID: 2, X: 150; Y: 300; Z: 300,
ID: 3, X: 300; Y: 200; Z: 100,
ID: 4, X: 50; Y: 100; Z: 200
How could I do it? What are the maths behind it? If it helps, I already have the following code:
var returnVehicles = [];
mp.vehicles.forEachInRange(player.position, 100, (vehicle) => {
if(vehicle.ownerID == player.id) {
returnVehicles.push(vehicle.position, vehicle.id);
}
}
);
It loops through the vehicles in a range of a 100 and adds into an array the IDs and positions of the ones that belong to the player. However, I don't know what to do with this.
Someone recommend me the .sort() method, but that doesn't seem to work, as it only gets the smallest coordinate, not the nearest.
@EDIT: MY FULL CODE
function distance3D(posA, posB) {
const dX = posA.X - posB.X;
const dY = posA.Y - posB.Y;
const dZ = posA.Z - posB.Z;
return Math.sqrt(dX * dX + dY * dY + dZ * dZ);
}
const vehiclesAndDistances = [];
function lockPlayerVehicle (player) {
let vehicle = player.vehicle;
if (vehicle) {
//IRRELEVANT
}
else {
mp.vehicles.forEachInRange(player.position, 40, (vehicle) => {
if(vehicle.ownerID == player.id) {
vehiclesAndDistances.push({vehicle, distance: distance3D(player, vehicle),});
}
}
);
vehiclesAndDistances.sort((a, b) => a.distance - b.distance);
player.outputChatBox("Lista Pequena: " + String(vehiclesAndDistances[0]));
console.log(vehiclesAndDistances[0], vehiclesAndDistances[0].vehicle.model)
};
}
mp.events.add("keypress:DOWNARROW", lockPlayerVehicle);