// Originally by ThatOneUpGuy#2573

local function doboing(mobj, line)
	if not mobj.player or not mobj.player.valid then
		return
	end

	mobj.rollangle = ANGLE_90

	mobj.player.viewrollangle = ANGLE_270

	mobj.angle = R_PointToAngle2(0, 0, line.dx, line.dy) - ANGLE_180

	mobj.state = S_PLAY_RUN

	mobj.momz = sin(mobj.player.aiming) * 50
end

local function boingy(mobj, line)
	if P_IsObjectOnGround(mobj) then
		return
	end

	if (mobj.player.pflags & PF_THOKKED) then
		return
	end

    local cursec = line.frontsector
    if mobj.subsector.sector == cursec then cursec = line.backsector end

    if not cursec then
		doboing(mobj, line)
        return true
    end
	
    local fheight = cursec.floorheight
    local cheight = cursec.ceilingheight

    if cursec.f_slope then
        fheight = P_GetZAt(cursec.f_slope, mobj.x + mobj.momx, mobj.y + mobj.momy)
    end
    if cursec.c_slope then
        cheight = P_GetZAt(cursec.c_slope, mobj.x + mobj.momx, mobj.y + mobj.momy)
    end

    mobj.curline = line

    if (mobj.z + mobj.height/2 < fheight or mobj.z + mobj.height/2 > cheight) then
		doboing(mobj, line)
        return true
    else
        for rov in cursec.ffloors() do
            if rov.flags & FF_SOLID then
                if (mobj.z + mobj.height/2 > rov.bottomheight and mobj.z + mobj.height/2 < rov.topheight) then
					doboing(mobj, line)
                    return true
                end
            end
        end
    end 
end

addHook("MobjLineCollide", function(mobj, line)
	boingy(mobj, line)
end, MT_PLAYER)

addHook("ThinkFrame", do
	for player in players.iterate
		if player.mo and player.mo.valid
			if P_IsObjectOnGround(player.mo)
				player.mo.rollangle = 0
				player.viewrollangle = 0
			end
			if player.mo.rollangle != 0
				if not (player.pflags & PF_THOKKED)
					P_InstaThrust(player.mo,player.mo.angle-ANGLE_45, 60*FRACUNIT)
				else
					P_InstaThrust(player.mo,player.mo.angle+ANGLE_45, 20*FRACUNIT)
					player.mo.state = S_PLAY_FALL
					player.mo.rollangle = 0
					player.viewrollangle = 0
				end
			end
		end
	end
end)