#back to spawn

1 messages · Page 1 of 1 (latest)

exotic mango
#
const { system, Player, Vector3 } = require('@minecraft/server')

/**
 * Teleport sequence promise will wait a given amount of time and return true if teleportation
 * was successful. If the player moves too far from the start location it fails the next second
 * and returns false for a failure.
 * 
 * @param {Player} player The player attempting to teleport
 * @param {number} time Amount of seconds for the teleport sequence delay
 * @returns {Promise} Bool promise with the teleport sequence success state
 */
function teleportSequence(player, time) {
    const teleportLocation = player.location
    let timeRemaining = time

    /**
     *
     * @returns {number} The distance from the start sequence start location and the player's current location
     */
    function getDistanceFromStart() {
        return Math.sqrt(
            Math.pow(teleportLocation.x - player.location.x, 2),
            Math.pow(teleportLocation.y - player.location.y, 2),
            Math.pow(teleportLocation.z - player.location.z, 2)
        )
    }

    return new Promise((resolve) => {
        function sequenceStep() {
            // If the player is too far from the start sequence location, resolve false for fail
            // and do NOT continue loop logic
            if (getDistanceFromStart() > 1) {
                resolve(false)
                return
            }

            // If the time remaining reached 0, our sequence is completed and we can return true
            // for success
            if (timeRemaining == 0) {
                resolve(true)
                return
            }

            // Update the player on the current teleport time and decrease our time remaining
            player.sendMessage(`Teleport in ${timeRemaining} seconds!`)
            timeRemaining -= 1

            // Rerun our logic next second (20 ticks) till completed
            system.runTimeout(sequenceStep, 20)
        }

        // Initial run of sequence needs no delay, will update the player's time remaining with
        // the base time required. (eg: 5, 4, 3, 2, 1)
        system.run(sequenceStep)
    })
}

/**
 * Teleport a player with a 5 second count down sequence that cancels if the player moves to
 * far from the initial location
 * 
 * @param {Player} player Player being teleported
 * @param {Vector3} to Teleport location
 */
async function doPlayerTeleport(player, to) {
    if (await teleportSequence(player, 5)) {
        player.teleport(to)
        player.sendMessage('Teleport successful!')
    } else {
        player.sendMessage('Failed to teleport!')
    }
}
slender cargo
#

Just do

import {} from "@minecraft/server"```