How can I get a player's last location? For example, if a player is teleported from coordinates (728, 28, 8289) to (178, 68, 718), they should be able to return to their previous location (728, 28, 8289) by typing !back in chat. Additionally, if a player dies and types !back in chat, they should be teleported to their last location.
#Getting Player's Last Location
1 messages · Page 1 of 1 (latest)
When executing a command specific for teleporting them, you can log their current location prior to teleporting them. Then use that stored log to return them back later if need be.
you can save player's coordinates before actions like these in dynamic property for these events, then teleport player to this saved data
If you only want to get their last location on death and/or when they use a command then do what the fellows above me said, but if you wanna save the last location even when they use the command /tp, then use this script:
import { system } from "@minecraft/server";
const min_dist = 10; // amount of blocks they have to pass before saving their location (in an instant)
system.runInterval(() => {
let players = world.getPlayers();
for (let i = 0; i < players.length; i++) {
checkDistance(players[i]);
}
}, 20);
const locations = new Map();
const backLocs = new Map();
function checkDistance(player) {
if (!locations.has(player.id)) {
locations.set(player.id, player.location);
return;
}
const savedLoc = locations.get(player.id), currentLoc = player.location, distance =
Math.abs(currentLoc.x - savedLoc.x) +
Math.abs(currentLoc.y - savedLoc.y) +
Math.abs(currentLoc.z - savedLoc.z);
if (distance >= min_dist) {
backLocs.set(player.id, location.get(player.id));
}
locations.set(player.id, player.location); // Update the saved location each check
}
What does this do? It saves two locations, one that is saved no matter what each second, basically it will be saved even if you are walking. And the backLoc only is saved if your last saved location (saved a second ago) and your current location are like 10+ blocks then you have teleported and it will save your location (last saved location, not this location) in the backLoc
Now this can be flagged if you use ender pearls, tnt launchers, and elytras but you can do some extra filtering to make sure it's only the tp command
I hope this helps.