减少玩家生命值的陷阱是可以用条件语句编写的有趣游戏元素。通过创建一个部分来设置触摸时玩家的生命值为零的条件来练习使用条件。
设置陷阱
陷阱在以移动为基础的挑战中的体验中表现异常出色,例如障碍赛。这些步骤将通过设置必要的变量和函数来开始。尽可能多地先不看代码盒进行操作。
创建并命名陷阱部分。将脚本插入到部分中。
在脚本中,添加描述性评论,然后使用变量来引用脚本的父元素级。
-- 如果玩家触碰这一部分,将他们的生命值设置为 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 类型的对象。玩家可能只用他们的虚拟形象的一部分触摸陷阱,因此必须设置变量以找到触摸部分的父辈并搜索它是否是人形。
在 onTouch() 中,输入 local character = otherPart.Parent .
local trapPart = script.Parentlocal function onTouch(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 语句进行检查
如果找到了一个人形怪物,则将人形怪物的健康设置为零。
使用 if 声明来检查是否成功将 Humanoid 分配到 local humanoid .
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到了一个人形怪物if humanoid thenendendtrapPart.Touched:Connect(onTouch)添加打印声明并检查目前的代码。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到了一个人形怪物if humanoid thenprint("Found a Humanoid")endendtrapPart.Touched:Connect(onTouch)运行 代码,检查您是否能够在玩家触摸零件时随时查看输出。
更改玩家的生命值
如果声明是真实的,你可以使用相同的人形变量将玩家的健康设置为 0。
在 then 和 end 之间,输入 humanoid.Health = 0 .
完成的脚本local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- 评估是否找到了一个人形怪物if humanoid thenprint("Found a Humanoid")humanoid.Health = 0endendtrapPart.Touched:Connect(onTouch)测试陷阱。
摘要
这个陷阱部分使用条件检测出人形部件,并将人形的健康设置为零。该脚本是对以前的陷阱脚本的改进,无论是什么,都会摧毁任何触碰对象。
然而,它仍然有一些缺陷。人形怪物不仅仅存在于玩家中。非玩家角色中也存在人形怪物。该脚本也只能将玩家的健康设置为零。您可以尝试减少少量生命值,但可能会更快地减少生命值,不如预期的那样。之后的课程提供进一步的改进,以提供更多控制玩家的生命值被扣除的方式。