--[[if (script.Parent.Active) then
	script.Parent.Name = "RESELECT"
	while (script.Parent.Active) do wait() end
end
script.Parent.Name = "Plane"]]


function changeGear()
	gear = (not gear)
	for _,v in pairs(gearParts) do
		v.Transparency,v.Reflectance,v.CanCollide = (gear and v.Trans.Value or 1),(gear and v.Ref.Value or 0),(gear and v.Collide.Value or false)	-- Learning how to code like this is extremely useful
	end
end

function updateGui(taxiing,stalling)
	panel.Off.Visible = (not on)
	panel.Taxi.Visible,panel.Stall.Visible = taxiing,(not taxiing and stalling)
	if ((realSpeed > -10000) and (realSpeed < 10000)) then
		panel.Speed.Value.Text = tostring(math.floor(realSpeed+0.5))
	end
	panel.Altitude.Value.Text = tostring(math.floor(main.Position.y+0.5)) - 8
	panel.Throttle.Bar.Amount.Size = UDim2.new(throttle,0,1,0)
end

function taxi()	-- Check to see if the plane is on the ground or not
	return (currentSpeed <= stallSpeed and game.Workspace:findPartOnRay(Ray.new(main.Position,Vector3.new(0,-lowestPoint,0)),plane))	-- Make sure plane is on a surface
end

function stall()	-- Originally set as a giant ternary operation, but got WAY too complex, so I decided to break it down for my own sanity
	if ((altRestrict) and (main.Position.y > altMax)) then return true end
	local diff = ((realSpeed-stallSpeed)/200)
	diff = (diff > 0.9 and 0.9 or diff)
	local check = {	-- Table placed here so I could easily add new 'checks' at ease. If anything in this table is 'true,' then the plane will be considered to be taxiing
		(currentSpeed <= stallSpeed);
		(main.CFrame.lookVector.y > (realSpeed < stallSpeed and -1 or -diff));
	}
	for _,c in pairs(check) do
		if (not c) then return false end
	end
	return true
end

function fly(m)	-- Main function that controls all of the flying stuff. Very messy.
	flying = true
	local pos,t = main.Position,time()
	local lastStall = false
	while ((flying) and (not dead)) do
		--realSpeed = ((pos-main.Position).magnitude/(time()-t))	-- Calculate "real" speed
		realSpeed = main.Velocity.Magnitude
		pos,t = main.Position,time()
		local max = (maxSpeed+(-main.CFrame.lookVector.y*speedVary))	-- Speed variety based on the pitch of the aircraft
		desiredSpeed = (max*(on and throttle or 0))	-- Find speed based on throttle
		local change = (desiredSpeed > currentSpeed and 1 or -1)	-- Decide between accelerating or decelerating
		currentSpeed = (currentSpeed+(accel*change))	-- Calculate new speed