如果/然后练习使用陷阱

*此内容使用人工智能(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 类型的对象。玩家可能只用他们的虚拟形象的一部分触摸陷阱,因此必须设置变量以找到触摸部分的父辈并搜索它是否是人形。

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


    local trapPart = script.Parent
    local function onTouch(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 语句进行检查

如果找到了一个人形怪物,则将人形怪物的健康设置为零。

  1. 使用 if 声明来检查是否成功将 Humanoid 分配到 local humanoid .


    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("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")
    -- 评估是否找到了一个人形怪物
    if humanoid then
    print("Found a Humanoid")
    end
    end
    trapPart.Touched:Connect(onTouch)
  3. 运行 代码,检查您是否能够在玩家触摸零件时随时查看输出。

更改玩家的生命值

如果声明是真实的,你可以使用相同的人形变量将玩家的健康设置为 0。

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

    完成的脚本

    local trapPart = script.Parent
    local function onTouch(otherPart)
    local character = otherPart.Parent
    local humanoid = character:FindFirstChildWhichIsA("Humanoid")
    -- 评估是否找到了一个人形怪物
    if humanoid then
    print("Found a Humanoid")
    humanoid.Health = 0
    end
    end
    trapPart.Touched:Connect(onTouch)
  2. 测试陷阱。

摘要

这个陷阱部分使用条件检测出人形部件,并将人形的健康设置为零。该脚本是对以前的陷阱脚本的改进,无论是什么,都会摧毁任何触碰对象。

然而,它仍然有一些缺陷。人形怪物不仅仅存在于玩家中。非玩家角色中也存在人形怪物。该脚本也只能将玩家的健康设置为零。您可以尝试减少少量生命值,但可能会更快地减少生命值,不如预期的那样。之后的课程提供进一步的改进,以提供更多控制玩家的生命值被扣除的方式。