为什么我的飞行脚本无法正常运行?

Why is my flight script not functioning correctly?

我正在制作一个用于 ProtoSmasher 的飞行脚本,但它没有按预期工作。我希望它有一个切换按钮 (G),然后可以用一个按钮 (W) 飞行。相反,为了让它工作,我必须按住 W 然后按 G;但是如果我想放开w停在空中我就得再按G。

local plr = game:GetService("Players").LocalPlayer
local char = plr.Character
local hum = char.Humanoid
local Torso = char.HumanoidRootPart
local Mouse = plr:GetMouse()
local toggle = false
local wToggle = false

Mouse.KeyDown:Connect(function(key)
    if key == "w" then
        wToggle = true
    end
    if key == "g" then
        if toggle == false then
            toggle = true
            local BV = Instance.new("BodyVelocity",Torso)
            BV.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
            while wToggle == true do
                BV.Velocity = Mouse.Hit.lookVector*200
                wait()
            end
        end
        if toggle == true then
            toggle = false
            Torso:FindFirstChildOfClass("BodyVelocity"):remove()
        end
    end
end)

Mouse.KeyUp:Connect(function(key)
    if key == "w" then
        wToggle = false
    end
end)

看起来您正在尝试连接到键盘按键,但您是在鼠标按键按下的事件侦听器中这样做的。

尝试这样的事情:

local isFlying = false

local function onKeyPress(actionName, userInputState, inputObject)
    local isKeyDown = userInputState == Enum.UserInputState.Begin
    local isKeyUp = userInputState == Enum.UserInputState.End

    if actionName == "toggleFlight" then
        if isKeyUp then
            isFlying = not isFlying
        end

    elseif actionName == "fly" then
        if isKeyDown then
            -- start flying forward
        elseif isKeyUp then
            -- stop flying
        end
    end
end

-- listen for keyboard input
game.ContextActionService:BindAction("toggleFlight", onKeyPress, false, Enum.KeyCode.G)
game.ContextActionService:BindAction("fly",          onKeyPress, false, Enum.KeyCode.W)