How to Respawn a Player

When a player dies they are put into a ragdoll state. Which prevents them from moving anywhere. You are responsible for what happens to the player when they die in your game mode. There is no default behavior determining what will happen when a player dies.

We're going to use this section to simply respawn the player after a set amount of time.

Handling Death

We are going to check if the player.id is an object key for the deadPlayers object. This will determine whether or not they have died multiple times and prevent any additional duplication of death events.

Then we are going to introduce the player.id to the object to mark them as dead.

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

alt.on('playerDeath', handleDeath);

export const DeadPlayers = {};

/**
 * @param {alt.Player} player
 */
function handleDeath(player) {
    // If it exists they are already dead.
    if (deadPlayers[player.id]) {
        return;
    }

    // Mark the player as dead.
    deadPlayers[player.id] = true;
}

What we've done is added a single reference to the player.id inside of DeadPlayers. Which is accessible by calling deadPlayers[player.id]. If this does not come back as undefined that means that the player has died and introduced a value into the object.

We can now expand on this concept and introduce a respawn timeout to the object instead of a boolean. This will give us better control over what happens while a player is waiting to be respawned.

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

alt.on('playerDeath', handleDeath);

export const DeadPlayers = {};
const TimeBetweenRespawn = 5000; // 5 Seconds

/**
 * @param {alt.Player} player
 */
function handleDeath(player) {
    if (deadPlayers[player.id]) {
        return;
    }

    deadPlayers[player.id] = alt.setTimeout(() => {
        // Check if the player still has an entry.
        if (deadPlayers[player.id]) {
            delete deadPlayers[player.id];
        }

        // Check if the player hasn't just left the server yet.
        if (!player || !player.valid) {
            return;
        }

        player.spawn(0, 0, 0, 0); // Respawn the player.
    }, TimeBetweenRespawn);
}

Now that we've added the code to respawn the player after 5s or 5000ms. We now have a Timeout that we can cancel if we want to interrupt their ability to respawn.

An example of interrupting the respawn and leaving them in ragdoll mode forever can be done by calling a function such as...

export function cancelRespawn(player) {
    // Check if an entry exists for a player respawn.
    if (!deadPlayers[player.id]) {
        return;
    }

    // This cancels the timeout from ever being finished.
    alt.clearTimeout(deadPlayers[player.id]);
    delete deadPlayers[player.id];
}

This is just a basic example of how to handle respawning.

Written by Stuyk

results matching ""

    No results matching ""