Code issues - how teleport player to savedPosition on respawn

Hello! I would like to know what I am doing wrong. I would like to save the player’s position when the function savePlayerPosition() is executed, and then (after the player dies or respawns) teleport the player to the saved position. How can I do that? :pray:

server-script:

-- Function to save the player's position to DataStore
local function savePlayerPosition(player)
	-- Check if the player has a character
	local character = player.Character
	if not character then
		return nil 
	end

	-- Get the player's position as a string
	local playerPosition = tostring(character.HumanoidRootPart.Position)

	-- Store player's position in DataStore
	local DataStoreService = game:GetService("DataStoreService")
	local playerDataStore = DataStoreService:GetDataStore("PlayerPositions")
	local success, errorMessage = pcall(function()
		playerDataStore:SetAsync(player.UserId, playerPosition)
	end)
	if not success then
		warn("Failed to save player position to DataStore:", errorMessage)
		return nil 
	end

	return playerPosition  -- Return the saved position
end

-- Function to handle the player's respawn
local function onPlayerRespawn(character)
	-- Get the player's saved position from DataStore
	local player = game.Players:GetPlayerFromCharacter(character)
	local playerPosition = savePlayerPosition(player)
	if playerPosition then
		-- Parse the position string
		local x, y, z = playerPosition:match("([^,]+),([^,]+),([^,]+)")
		if x and y and z then
			-- Teleport the player to the saved position
			character:SetPrimaryPartCFrame(CFrame.new(Vector3.new(tonumber(x), tonumber(y), tonumber(z))))
		else
			warn("Invalid player position format:", playerPosition)
		end
	else
		warn("No position saved for player:", player.Name)
	end
end

-- Function to handle when a player joins the game
local function onPlayerAdded(player)
	player.CharacterAdded:Connect(function(character)
		-- Listen for when the player's character dies
		character.Humanoid.Died:Connect(function()
			-- Teleport the player to their saved position upon respawn
			onPlayerRespawn(character)
		end)
	end)
end

-- Connect the onPlayerAdded function to the PlayerAdded event
game.Players.PlayerAdded:Connect(onPlayerAdded)

-- Handle players that were already in the game when the script runs
for _, player in ipairs(game.Players:GetPlayers()) do
	onPlayerAdded(player)
end
1 Like

What output are you getting, a error, or nothing, or a bug?

1 Like

The .Died Event fires when the player’s health changes to 0, the CharacterAdded Event fires when the character respawns. That means you are currently detecting when the character is added, then you wait until they die again, and while they are dead, you take them to their new position.

Also, when you do local playerPosition = savePlayerPosition you aren’t getting the playerposition, you are only calling the function that actually saves their current position to the data store.

What you actually want to do is:

  1. Detect the .Died Event and save their current position
  2. Detect CharacterAdded and position them.

So, add a function that gets the last position:

-- Functionm to get the saved player position
local function getPlayerPosition(player)
	local DataStoreService = game:GetService("DataStoreService")
	local playerDataStore = DataStoreService:GetDataStore("PlayerPositions")
	
	return playerDataStore:GetAsync(player.UserId) or nil
end

Then edit the onPlayerRespawn function to call the get function, not the save function:

local function onPlayerRespawn(character)
	-- Get the player's saved position from DataStore
	local player = game.Players:GetPlayerFromCharacter(character)
	local playerPosition = getPlayerPosition(player)
...

And Lastly handle the CharacterAdded and .Died events properly

local function onPlayerAdded(player)
	player.CharacterAdded:Connect(function(character)
		onPlayerRespawn(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			savePlayerPosition(player)
		end)
	end)
end

I tested it and it worked, if there’s any more issues, let me know.

2 Likes

Oh, thank you so much, this worked perfectly! But sorry, one more question, I hope I’m not bothering you… I’d like to know, how can I make it so that the last saved position is stored when the player touched the checkpoint and respawn at the last checkpoint touched?

-- Coroutine function to enable/disable visual effects (VFX) for a specified duration
local function enableVFXForDuration(arcsVFX, duration)
	if arcsVFX then
		arcsVFX.Enabled = true
		wait(duration)
		arcsVFX.Enabled = false
	else
		warn("ArcsVFX not found!")
	end
end

-- Function to change the colors of checkpoint parts
local function changeColors(checkpointParts, partColors)
	for i, part in ipairs(checkpointParts) do
		part.Color = partColors[i]
	end
end

-- Coroutine function to play animation from a humanoid for a specified duration
local function playAnimationFromHumanoid(humanoid, animationId, duration)
	if animationId then
		local animationTrack = Instance.new("Animation")
		animationTrack.AnimationId = animationId
		local animation = humanoid:LoadAnimation(animationTrack)
		if animation then
			animation:Play()
			wait(duration)
			animation:Stop()
		else
			warn("Failed to load animation - sanitized ID:", animationId)
		end
	else
		warn("Animation ID not provided.")
	end
end

-- Coroutine function to play a sound for a specified duration
local function playSound(soundId, duration)
	if soundId then
		local sound = Instance.new("Sound")
		sound.SoundId = soundId
		sound.Parent = game.Workspace
		sound:Play()
		wait(duration)
		sound:Destroy()
	else
		warn("Sound ID not provided.")
	end
end

-- Functionm to get the saved player position
local function getPlayerPosition(player)
	local DataStoreService = game:GetService("DataStoreService")
	local playerDataStore = DataStoreService:GetDataStore("PlayerPositions")

	return playerDataStore:GetAsync(player.UserId) or nil
end

-- Function to save the player's position to DataStore
local function savePlayerPosition(player)
	-- Check if the player has a character
	local character = player.Character
	if not character then
		return nil 
	end

	-- Get the player's position as a string
	local playerPosition = tostring(character.HumanoidRootPart.Position)

	-- Store player's position in DataStore
	local DataStoreService = game:GetService("DataStoreService")
	local playerDataStore = DataStoreService:GetDataStore("PlayerPositions")
	local success, errorMessage = pcall(function()
		playerDataStore:SetAsync(player.UserId, playerPosition)
	end)
	if not success then
		warn("Failed to save player position to DataStore:", errorMessage)
		return nil 
	end

	return playerPosition  -- Return the saved position
end

-- Function to handle the player's respawn
local function onPlayerRespawn(character)
	-- Get the player's saved position from DataStore
	local player = game.Players:GetPlayerFromCharacter(character)
	local playerPosition = getPlayerPosition(player)
	if playerPosition then
		-- Parse the position string
		local x, y, z = playerPosition:match("([^,]+),([^,]+),([^,]+)")
		if x and y and z then
			-- Teleport the player to the saved position
			character:SetPrimaryPartCFrame(CFrame.new(Vector3.new(tonumber(x), tonumber(y), tonumber(z))))
		else
			warn("Invalid player position format:", playerPosition)
		end
	else
		warn("No position saved for player:", player.Name)
	end
end

local function onPlayerAdded(player)
	player.CharacterAdded:Connect(function(character)
		onPlayerRespawn(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			savePlayerPosition(player)
		end)
	end)
end

-- Connect the onPlayerAdded function to the PlayerAdded event
game.Players.PlayerAdded:Connect(onPlayerAdded)

-- Handle players that were already in the game when the script runs
for _, player in ipairs(game.Players:GetPlayers()) do
	onPlayerAdded(player)
end

-- Define specific checkpoint objects here
local platform = script.Parent
local platformArea = platform.platformArea
local arcsVFX = script.Parent:FindFirstChild("B - Arcs v1 [C]").Middle.Arcs
local checkpointParts = {
	platform.Arrow,
	platform.Part1,
	platform.Part2,
	platform.Part3
}
local colorsToChange = {
	Color3.fromRGB(0, 255, 0),
	Color3.fromRGB(0, 255, 0),
	Color3.fromRGB(255, 255, 255),
	Color3.fromRGB(255, 255, 255)
}
local defaultColor = {
	Color3.fromRGB(196, 40, 28),
	Color3.fromRGB(248, 248, 248),
	Color3.fromRGB(196, 40, 28),
	Color3.fromRGB(248, 248, 248)
}

-- Variable to track if the event is already being processed
local debounce = false

local animationId = "rbxassetid://507771019"
local soundId = "rbxassetid://1843468464"

-- Connect the function to the Touched event of the checkpoint
platformArea.Touched:Connect(function(hit)
	if debounce then
		return -- If an event is already in progress, exit the function
	end
	debounce = true -- Mark that an event is in progress

	print("Part touched")

	-- Change the colors of checkpoint parts when touched
	changeColors(checkpointParts, colorsToChange)

	-- Check if the object that touched the part is a character (player)
	local character = hit.Parent:FindFirstChildOfClass("Humanoid")
	if character and game.Players:GetPlayerFromCharacter(hit.Parent) then
		print("Player character found")
		-- Call the coroutine functions with the player and the animation/sound parameters
		spawn(function()
			playAnimationFromHumanoid(character, animationId, 3) -- Duration of 3 seconds
		end)
		spawn(function()
			playSound(soundId, 3) -- Duration of 3 seconds
		end)
		spawn(function()
			enableVFXForDuration(arcsVFX, 3) -- Duration of 3 seconds
		end)
		savePlayerPosition(game.Players:GetPlayerFromCharacter(hit.Parent)) -- Save player position
	else
		print("Not a player character")
	end

	wait(2) -- Wait for a moment to prevent the event from firing multiple times quickly
	debounce = true -- Reset the event in progress indicator to allow it to fire again
end)

-- Connect the function to the TouchEnded event of the checkpoint
platformArea.TouchEnded:Connect(function()
	-- Reset the default colors when the checkpoint touch ends
	--changeColors(checkpointParts, defaultColor)

	-- Disable the VFX if it's currently active
	if arcsVFX then
		arcsVFX.Enabled = false
	end
end)

No problem. Just rewrite the code for respawning where they were last at. To do this you just need to remove the .Died event in the onPlayerAdded Function to stop the position from saving upon death and instead add something along the lines of this:

local Checkpoints = workspace.Checkpoints

for _, checkpoint in pairs(Checkpoints:GetChildren()) do
  checkpoint.Touched:Connect(function(hit)
    if hit and hit.Parent and hit.Parent:FindFirstChild("Humanoid") and game:GetService("Players"):GetPlayerFromCharacter(hit.Parent) then
      local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
      savePlayerPosition(player)
    end
  end)
end

Put this anywhere in your script where it will run at startup.

1 Like

It’s not working, or I think I implemented it incorrectly. Could you please hlpme pls?

First of all, you need to remove the Humanoid.Died Event from the onPlayerAdded function:

local function onPlayerAdded(player)
	player.CharacterAdded:Connect(function(character)
		onPlayerRespawn(character)
	end)
end

Now you can implement the for loop for the checkpoints somewhere below this. The Checkpoints variable should reference the folder containing all checkpoint parts, alternatively you can use tags and CollectionService to get all checkpoints. If its still not working can you tell me more about the issue? Also, please provide some information about how your game is setup, such as where the checkpoints are stored.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.