How to Spawn a Vehicle

Spawning a vehicle can be done by creating a new vehicle through the alt.Vehicle class. This should be done on server-side as this makes the vehicle accessible to all players and makes it visible for all players as well.

You should NEVER use natives to spawn vehicles unless it's for client-side only previewing or non-synchronized purposes.

Base Example

Below is a base function to create a simple vehicle based on player position and vehicle model.

/// <reference types="@altv/types-server" />
import * as alt from 'alt-server';

export function createVehicle(player, vehicleModel) {
    let vehicle;

    try {
        vehicle = new alt.Vehicle(vehicleModel, player.pos.x, player.pos.y, player.pos.z, 0, 0, 0);
    } catch (err) {
        console.error(`${vehicleModel} does not exist.`);
        throw err;
    }

    if (!vehicle) {
        console.error(`${vehicleModel} does not exist.`);
        return;
    }

    console.log('Spawned a vehicle');
    return vehicle;
}

Real World Example

Now depending on what is available in your server there are a ton of different ways to spawn a vehicle for a player. You can do it when they connect, when they die, when they type a command, etc. However, if you wish to do this by command you are going to need to install a chat resource as alt:V does not automatically come with a chat.

Below we will give the player a vehicle when they join the server.

alt.on('playerConnect', (player) => {
    const spawnedVehicle = createVehicle(player, 'infernus');

    if (!spawnedVehicle) {
        console.error('Vehicle could not be spawned.');
        return;
    }
});

A vehicle will likely spawn on top of the player and crush them, but hey at least you got a vehicle spawned.

Written by Stuyk

results matching ""

    No results matching ""