评估多个语句

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

如果语句可以有多个要求,这些要求需要在运行代码之前为真。关键字 and 允许你组合语句。以下代码首先评估两个加两个是否等于六,然后评估四是否不等于六。如果两个语句都为真,代码将运行。

-- 不会运行
if 2 + 2 == 6 and 4 ~= 6 then
print("两个语句都为真")
end
-- 会运行
if 4 + 2 == 6 and 4 ~= 6 then
print("两个语句都为真")
end

创建一个能量提升

能量提升是游戏内物品,可以赋予玩家特殊能力,如飞行、隐身或加速。这个能量提升将在每次触碰时提升玩家的行走速度。持续施加提升可能会使玩家速度过快,因此将使用 and 来控制上限行走速度。

设置能量提升

使用这段代码与一个简单的部件或模型,例如水晶、硬币或发光的霓虹球。

  1. 创建一个名为 Powerup 的新部件,并插入一个名为 WalkSpeedManager 的脚本。

  2. 声明一个名为 speedBoost 的变量,并将其分配给脚本的父对象。

    -- 触碰时给予临时速度提升
    local speedBoost = script.Parent
  3. 设置一个名为 onTouch 的函数,并将其连接到父对象的 Touched 事件。然后进行游戏测试并检查你的工作。

    local speedBoost = script.Parent
    local function onTouch(otherPart)
    print("某物触碰了 speedBoost")
    end
    speedBoost.Touched:Connect(onTouch)
  4. WalkSpeed 属性在 Humanoid 对象上找到。使用与创建陷阱部件时相同的模式,创建一个条件来检查 Humanoid 对象。

    查找 Humanoid 部件
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid then
    print("找到了一个 Humanoid")
    end
    end

加速玩家

每次触碰能量提升时,速度提升将使化身走得更快。这将迅速变得非常非常快。关键字 and 将确保玩家不会走得太快,只有在玩家的速度低于某个值时才启用速度提升。

  1. 如果找到了 Humanoid,获取当前的 WalkSpeed 值并加 10。进行游戏测试,你的化身每次触碰速度提升时都会变得更快。

    增加当前 WalkSpeed
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid then
    humanoid.WalkSpeed += 10
    end
    end
    speedBoost.Touched:Connect(onTouch)
  2. 在 if 语句中,使用关键字 and 添加第二个条件,要求当前的 WalkSpeed 值小于 50。添加提升后,最快的 WalkSpeed 值将是 60。

    检查当前 WalkSpeed 是否为 50 或更少
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    end

微调速度提升

每次触碰能量提升时都会调用 onTouch。每一步或最轻微的反弹都会触发 Touched 事件并调用连接的函数。部件的属性 CanTouch 可以防止 Touched 事件触发。利用 CanTouch,每次激活后将速度提升关闭一秒钟。

  1. 在应用提升后,将部件的 CanTouch 属性设置为 false。进行游戏测试,确保提升只应用一次。

    禁用速度提升
    local speedBoost = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    speedBoost.CanTouch = false
    end
    end
    speedBoost.Touched:Connect(onTouch)
  2. 使用 task.wait(1) 暂停脚本一秒钟,然后将 CanTouch 设置为 true。进行游戏测试,确保速度提升可以在一秒后重新应用。

    完成的脚本
    local speedBoost = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    if humanoid and humanoid.WalkSpeed <= 50 then
    humanoid.WalkSpeed += 10
    speedBoost.CanTouch = false
    task.wait(1)
    speedBoost.CanTouch = true
    end
    end
    speedBoost.Touched:Connect(onTouch)
  3. 在完成的脚本中玩弄这些值。WalkSpeed 可以达到 100。默认的 WalkSpeed 值是 16。

总结

关键字 and 可用于要求多个条件在运行代码块之前为真,例如一个值大于 0 且小于 100。或者如果存在一个 Humanoid 并且其 WalkSpeed 小于或等于 50。

©2026 Roblox Corporation、Roblox、Roblox 标志及 Powering Imagination 是我们在美国及其他国家或地区的注册与未注册商标。