减少玩家生命值的陷阱是一个有趣的游戏元素,可以通过条件语句进行编码。通过创建一个在被触碰时将玩家生命值设置为零的部件来练习使用条件语句。
设置陷阱
陷阱在基于移动的挑战游戏中表现得非常好,比如障碍赛。这些步骤将从设置必要的变量和函数开始。尽量在不查看代码框的情况下完成尽可能多的内容。
创建并命名一个陷阱部件。在部件中插入一个脚本。
在脚本中添加一个描述性注释,然后使用一个变量引用脚本的父级。
-- 如果玩家触碰这个部件,将他们的生命值设置为 0local trapPart = script.Parent创建一个名为 onTouch() 的函数,带有一个名为 otherPart 的参数。
-- 如果玩家触碰这个部件,将他们的生命值设置为 0local trapPart = script.Parentlocal function onTouch(otherPart)end将函数连接到陷阱部件的 Touched 事件,以便在有东西触碰该部件时运行。
local trapPart = script.Parentlocal function onTouch(otherPart)endtrapPart.Touched:Connect(onTouch)
检查玩家触碰
请记住,参数 otherPart 记录触碰陷阱部件的任何内容,这可能是玩家的一部分或只是基础板。
为了确保陷阱只会摧毁玩家,而不会摧毁随机的装饰物品,使用 if/then 语句检查 otherPart 中是否包含 Humanoid 对象。
查找特定对象
函数 FindFirstChildWhichIsA() 可用于查找特定类型的对象,这很方便,因为我们正在寻找 Humanoid 类型的对象。玩家可能只用他们头像的一部分触碰陷阱,因此必须设置一个变量来查找触碰部件的父级并在其中搜索 Humanoid。
在 onTouch() 中,输入 local character = otherPart.Parent。
local trapPart = script.Parentlocal function onTouch(otherPart)-- 查找 otherPart 的父对象local character = otherPart.ParentendtrapPart.Touched:Connect(onTouch)检查 character 是否具有 Humanoid,输入:
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")endtrapPart.Touched:Connect(onTouch)
使用 if 语句检查
如果找到 Humanoid,则将 Humanoid 的生命值设置为零。
使用 if 语句检查是否成功将 Humanoid 分配给 local humanoid。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到 Humanoidif humanoid thenendendtrapPart.Touched:Connect(onTouch)添加一个打印语句并检查到目前为止的代码。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到 Humanoidif humanoid thenprint("找到一个 Humanoid")endendtrapPart.Touched:Connect(onTouch)运行 代码并检查每当玩家触碰该部件时是否可以看到输出。
改变玩家的生命值
如果语句为真,您可以使用相同的 humanoid 变量将玩家的生命值设置为 0。
在 then 和 end 之间输入 humanoid.Health = 0。
完成的脚本local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到 Humanoidif humanoid thenprint("找到一个 Humanoid")humanoid.Health = 0endendtrapPart.Touched:Connect(onTouch)测试陷阱。
总结
这个陷阱部件使用条件语句来检测 Humanoid 部件并将 Humanoid 的生命值设置为零。这个脚本是对之前陷阱脚本的改进,后者无论触碰的对象是什么都会摧毁它。
然而,它仍然有一些缺陷。Humanoid 不仅存在于玩家中。Humanoid 也存在于不可玩角色中。该脚本也仅适用于将玩家的生命值设置为零。您可以尝试减少少量生命值,但可能会比预期更快地减少生命值。后面的课程提供了进一步的改进,以更好地控制从玩家身上减少多少生命值。