如果/那么练习与陷阱

*此内容使用人工智能(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 变量将玩家的生命值设置为零。

  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 不仅存在于玩家中,还存在于非玩家角色中。该脚本也只能将玩家的生命值设置为零。你可以尝试减少一小部分生命值,但很可能会比预期更快地减少生命值。后续的课程提供更进一步的改进,以更好地控制从玩家身上减少的生命值数量。

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