-- Aleph one Lua script header
Triggers = {}

-- When this script is first loaded at the beginning of each level, this should be true.
firstFrame = true

-- Save the current level's index.
currLevelIndex = Level.index

-- Instantiate blank arrays that hold player data.
p_X = {}
p_Y = {}
p_D = {}


-- "Triggers.idle()" IS THE FUNCTION CALLED 30x PER SECOND DURING GAMEPLAY
-- WHAT IT DOES:
-- If any player teleports in, fade their screen just like in the original Marathon 1 game.
function Triggers.idle()


	-- Start the player counter at 1 before the for loop.
	playerCount = 1

	-- For each player object p in all active players (p iterates through the index of all active players during a running game session) ...
	for p in Players() do


	-- Case: Player teleports into a level

		-- If the level has just begun (teleporting into the level)
		-- AND
		-- If the level is not the first, and not a network map (so basically for all single player levels but the first in the standard M1 single player scenario)
		if (firstFrame) and (currLevelIndex < 27) and not (currLevelIndex == 0) then

			-- Fade player p's screen to the "teleport in" fader
			p:fade_screen("bright")

			-- Save player p's current XY coordinates on the map.
			p_X[playerCount] = p.x
			p_Y[playerCount] = p.y

			-- Set firstFrame to false, so as never to run this if statement again until the beginning of the next level.
			firstFrame = false

		-- End level just begun
		end

		-- If the level wasn't one of the above (like level 0 or a net level)
		if (firstFrame) then

			-- Save player p's current XY coordinates on the map.
			p_X[playerCount] = p.x
			p_Y[playerCount] = p.y

			-- Set firstFrame to false, so as never to run this if statement again until the beginning of the next level.
			firstFrame = false

		-- End level just begun
		end



	-- Case: Player teleports within a level

		-- Compare the player's change in position over the last two ticks (1 tick = 1/30 seconds) of gameplay
		p_D[playerCount] = math.sqrt( (p_X[playerCount] - p.x)^2 + (p_Y[playerCount] - p.y)^2 )

		-- If any player traverses greater than 1 world unit over the course of 1 tick (only possible through teleportation... or a really big explosion maybe?)
		if (p_D[playerCount] > 1) then

			-- Fade the player's screen to the "teleport in" fader
			p:fade_screen("bright")

		end

		-- Save player p's current XY coordinates on the map.
		p_X[playerCount] = p.x
		p_Y[playerCount] = p.y

		-- Increment the player counter:
		playerCount = playerCount + 1

	-- End for each active player p
	end


-- End function Triggers.idle()
end