Need help, I respawn in the air

Hello, so I have a script where you respawn where you die, can someone assist me if I die while in the air it won’t respawn me in the air and it will find the last thing i was on and respawn me if you get the gist.

Script:

local runService = game:GetService("RunService")
local deathPos = {}

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		runService.Stepped:Wait()

		if deathPos[player] then
			character:PivotTo(deathPos[player])
		end

		local humanoid = character:WaitForChild("Humanoid")

		humanoid.Died:Connect(function()
			deathPos[player] = character.PrimaryPart.CFrame
		end)
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	deathPos[player] = nil
end)

The humanoid has a property where it detects what material its standing on, one of them is air and i think another one is water, not sure tho

You can tie it to the heartbeat event, meaning:

RunService.Heartbeat:Connect(function(deltaTime()
for i, player in Players:GetPlayers() do
if typeof(player.Character) == “Instance” and player.Character.Humanoid.FloorMaterial ~= (Enum.Marerial.Air or Enum.Material.Water) then
deathPos[player] = player.Character.PrimaryPart.CFrame
end
end
end)

Theres some optimization to be done here, but i think it works fine like that, maybe put it inside a pcall function; the loop code, like erm, not the loop itself but inside the loop

You could try, that upon player dies, you do a raycast from the coordinates where the player died, and aiming it to the ground, on hit you get the coordinates that are on the ground so you can respawn the player in there instead of the air coordinates

So do you mean if you walk off a ledge and die it’ll respawn you at that ledge?

Try raycasting downward every half second or so while you are moving (instead of using a while true do loop), and storing the value of the last Position as a variable.
When your raycast returns nil then don’t save over that variable value. If the player dies then spawn them at the last stored variable Position.