使用陷阱进行 if/then 练习

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

减少玩家生命值的陷阱是一个有趣的游戏元素,可以通过条件语句进行编码。通过创建一个在被触碰时将玩家生命值设置为零的部件来练习使用条件语句。

设置陷阱

陷阱在基于移动的挑战游戏中表现得非常好,比如障碍赛。这些步骤将从设置必要的变量和函数开始。尽量在不查看代码框的情况下完成尽可能多的内容。

  1. 创建并命名一个陷阱部件。在部件中插入一个脚本。

  2. 在脚本中添加一个描述性注释,然后使用一个变量引用脚本的父级。

    -- 如果玩家触碰这个部件,将他们的生命值设置为 0
    local trapPart = script.Parent
  3. 创建一个名为 onTouch() 的函数,带有一个名为 otherPart 的参数。

    -- 如果玩家触碰这个部件,将他们的生命值设置为 0
    local trapPart = script.Parent
    local function onTouch(otherPart)
    end
  4. 将函数连接到陷阱部件的 Touched 事件,以便在有东西触碰该部件时运行。

    local trapPart = script.Parent
    local function onTouch(otherPart)
    end
    trapPart.Touched:Connect(onTouch)

检查玩家触碰

请记住,参数 otherPart 记录触碰陷阱部件的任何内容,这可能是玩家的一部分或只是基础板。

为了确保陷阱只会摧毁玩家,而不会摧毁随机的装饰物品,使用 if/then 语句检查 otherPart 中是否包含 Humanoid 对象。

查找特定对象

函数 FindFirstChildWhichIsA() 可用于查找特定类型的对象,这很方便,因为我们正在寻找 Humanoid 类型的对象。玩家可能只用他们头像的一部分触碰陷阱,因此必须设置一个变量来查找触碰部件的父级并在其中搜索 Humanoid。

  1. onTouch() 中,输入 local character = otherPart.Parent

    local trapPart = script.Parent
    local function onTouch(otherPart)
    -- 查找 otherPart 的父对象
    local character = otherPart.Parent
    end
    trapPart.Touched:Connect(onTouch)
  2. 检查 character 是否具有 Humanoid,输入:

    local humanoid = character:FindFirstChildWhichIsA("Humanoid")

    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    end
    trapPart.Touched:Connect(onTouch)

使用 if 语句检查

如果找到 Humanoid,则将 Humanoid 的生命值设置为零。

  1. 使用 if 语句检查是否成功将 Humanoid 分配给 local humanoid

    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 评估是否找到 Humanoid
    if humanoid then
    end
    end
    trapPart.Touched:Connect(onTouch)
  2. 添加一个打印语句并检查到目前为止的代码。

    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 评估是否找到 Humanoid
    if humanoid then
    print("找到一个 Humanoid")
    end
    end
    trapPart.Touched:Connect(onTouch)
  3. 运行 代码并检查每当玩家触碰该部件时是否可以看到输出。

改变玩家的生命值

如果语句为真,您可以使用相同的 humanoid 变量将玩家的生命值设置为 0。

  1. thenend 之间输入 humanoid.Health = 0

    完成的脚本
    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 评估是否找到 Humanoid
    if humanoid then
    print("找到一个 Humanoid")
    humanoid.Health = 0
    end
    end
    trapPart.Touched:Connect(onTouch)
  2. 测试陷阱。

总结

这个陷阱部件使用条件语句来检测 Humanoid 部件并将 Humanoid 的生命值设置为零。这个脚本是对之前陷阱脚本的改进,后者无论触碰的对象是什么都会摧毁它。

然而,它仍然有一些缺陷。Humanoid 不仅存在于玩家中。Humanoid 也存在于不可玩角色中。该脚本也仅适用于将玩家的生命值设置为零。您可以尝试减少少量生命值,但可能会比预期更快地减少生命值。后面的课程提供了进一步的改进,以更好地控制从玩家身上减少多少生命值。

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