quhluh

flying code in lua for roblox game

Apr 3rd, 2023
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.16 KB | Gaming | 0 0
  1. -- Define a variable to keep track of whether the player is flying or not
  2. local isFlying = false
  3.  
  4. -- Function to enable flying
  5. function enableFlying()
  6.     isFlying = true
  7.     game:GetService("Players").LocalPlayer.Character.Humanoid:ChangeState(Enum.HumanoidStateType.Physics)
  8.     -- Set the gravity to zero so the player can float in the air
  9.     game.Workspace.Gravity = Vector3.new(0,0,0)
  10. end
  11.  
  12. -- Function to disable flying
  13. function disableFlying()
  14.     isFlying = false
  15.     game:GetService("Players").LocalPlayer.Character.Humanoid:ChangeState(Enum.HumanoidStateType.GettingUp)
  16.     -- Restore the gravity to its original value
  17.     game.Workspace.Gravity = Vector3.new(0,-workspace.Gravity,0)
  18. end
  19.  
  20. -- Check for user input to enable/disable flying
  21. game:GetService("UserInputService").InputBegan:Connect(function(input, processed)
  22.     if processed then return end
  23.     if input.KeyCode == Enum.KeyCode.Space then
  24.         if isFlying then
  25.             disableFlying()
  26.         else
  27.             enableFlying()
  28.         end
  29.     end
  30. end)
  31.  
  32. -- Update the player's position while flying
  33. game:GetService("RunService").RenderStepped:Connect(function(deltaTime)
  34.     if isFlying then
  35.         local player = game:GetService("Players").LocalPlayer
  36.         local camera = game.Workspace.CurrentCamera
  37.  
  38.         -- Get the input direction from the WASD keys and adjust for camera orientation
  39.         local inputDirection = (camera.CFrame.lookVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.W) and 1 or 0)
  40.             - camera.CFrame.rightVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.A) and 1 or 0)
  41.             + camera.CFrame.lookVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.S) and 1 or 0)
  42.             + camera.CFrame.rightVector * (game:GetService("UserInputService"):IsKeyDown(Enum.KeyCode.D) and 1 or 0)
  43.         )
  44.  
  45.         -- Normalize the input direction so that the player moves at a consistent speed
  46.         inputDirection = inputDirection.unit
  47.  
  48.         -- Move the player based on the input direction and the player's speed
  49.         player.Character.HumanoidRootPart.Velocity = inputDirection * 50
  50.     end
  51. end)
Advertisement
Add Comment
Please, Sign In to add comment