减少玩家生命值的陷阱是一个有趣的游戏元素,可以通过条件语句进行编码。通过创建一个在触碰时将玩家生命值设置为零的部件来练习使用条件语句。
设置陷阱
陷阱在基于移动的挑战(如障碍赛)体验中非常有效。以下步骤将开始设置必要的变量和函数。尽量在不查看代码框的情况下完成尽可能多的工作。
创建并命名一个陷阱部件。将脚本插入到该部件中。
在脚本中添加一个描述性注释,然后使用一个变量来引用脚本的父对象。
-- 如果玩家触碰此部件,则将其生命值设置为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 变量将玩家的生命值设置为零。
在 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 不仅存在于玩家中,还存在于非玩家角色中。该脚本也只能将玩家的生命值设置为零。你可以尝试减少一小部分生命值,但很可能会比预期更快地减少生命值。后续的课程提供更进一步的改进,以更好地控制从玩家身上减少的生命值数量。