Sign in to follow this  
Georgie

Deleting the closest vehicle

Recommended Posts

mp.events.addCommand("test", (player) => {
    let VehiclesPositionsArray = [];
    let VehiclesIDsArray = [];
    let VehiclesArray = mp.vehicles.toArray();
    let VehicleNumber = 0;
    let VehicleNumberArray = [];
    let VehicleNumberNow = 0;
    mp.vehicles.forEachInRange(player.position, 10,
        (vehicle) => {
            VehiclesPositionsArray.push(Math.hypot(player.position.- vehicle.position.x, player.position.- vehicle.position.y, player.position.- vehicle.position.z));
            console.log(`${Math.hypot(player.position.- vehicle.position.x, player.position.- vehicle.position.y, player.position.- vehicle.position.z)}`);
            VehiclesIDsArray.push(vehicle.id);
            VehicleNumberArray.push(VehicleNumber);
            VehicleNumber += 1;
        });
        let aVeh = VehiclesPositionsArray[0]
        for(let i = 0; i < VehicleNumberArray.length; i++)
        {
            if(aVeh > VehiclesPositionsArray[i])
            {
                aVeh = VehiclesPositionsArray[i];
                VehicleNumberNow = i;
            }
        }
        let vehForDest = VehiclesIDsArray[VehicleNumberNow];
        VehiclesArray[vehForDest].destroy();
});

By executing this command, the vehicle is deleted, first the closest, but then random, and not the nearest. What is the problem? Help)

Share this post


Link to post
Share on other sites
mp.events.addCommand('test', (player) => {
	let vehicles = []; // Create empty vehicles array
	mp.vehicles.forEachInRange(player.position, 10, (vehicle) => vehicles.push({playerPos: player.position, veh: vehicle})); // Push all vehicles in range along with player position on the empty array
	vehicles.sort(byEntityDistance); // Sort vehicles by its position
	vehicles.map((element) => element.veh); // Remove the playerPos from the array
	vehicles.forEach((vehicle) => vehicle.destroy()); // Destroy all vehicles in order
});

function byEntityDistance(a, b) {
	let entityA = a.veh.dist(a.playerPos);
	let entityB = b.veh.dist(b.playerPos);
	if (entityA > entityB)
		return 1;
	else if (entityB > entityA)
		return -1;
	else
		return 0;
}

Didn't test the code, but it's a way of doing what you seems to want.

Edited by Pilatus

Share this post


Link to post
Share on other sites

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
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.