quhluh icon

flying code in lua for roblox game

quhluh | 04/03/23 08:53:14 PM UTC | 0 ⭐ | 534 👁️ | Never ⏰ | [Roblox, lua, fly, free roblox account, flying, fly code]
Lua |

2.16 KB

|

Gaming

|

0 👍

/

0 👎

-- Define a variable to keep track of whether the player is flying or not
local isFlying = false
 
-- Function to enable flying
function enableFlying()
    isFlying = true
    game:GetService("Players").LocalPlayer.Character.Humanoid:ChangeState(Enum.HumanoidStateType.Physics)
    -- Set the gravity to zero so the player can float in the air
    game.Workspace.Gravity = Vector3.new(0,0,0)
end
 
-- Function to disable flying
function disableFlying()
    isFlying = false
    game:GetService("Players").LocalPlayer.Character.Humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
    -- Restore the gravity to its original value
    game.Workspace.Gravity = Vector3.new(0,-workspace.Gravity,0)
end
 
-- Check for user input to enable/disable flying
game:GetService("UserInputService").InputBegan:Connect(function(input, processed)
    if processed then return end
    if input.KeyCode == Enum.KeyCode.Space then
        if isFlying then
            disableFlying()
        else
            enableFlying()
        end
    end
end)
 
-- Update the player's position while flying
game:GetService("RunService").RenderStepped:Connect(function(deltaTime)
    if isFlying then
        local player = game:GetService("Players").LocalPlayer
        local camera = game.Workspace.CurrentCamera
 
        -- Get the input direction from the WASD keys and adjust for camera orientation
        local inputDirection = (camera.CFrame.lookVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.W) and 1 or 0)
            - camera.CFrame.rightVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.A) and 1 or 0)
            + camera.CFrame.lookVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.S) and 1 or 0)
            + camera.CFrame.rightVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.D) and 1 or 0)
        )
 
        -- Normalize the input direction so that the player moves at a consistent speed
        inputDirection = inputDirection.unit
 
        -- Move the player based on the input direction and the player's speed
        player.Character.HumanoidRootPart.Velocity = inputDirection * 50
    end
end)

Comments