如果语句可以有多个要求,只有在所有要求为真时才会执行代码。关键字 and 允许你组合语句。以下代码首先评估两个加两个是否等于六,然后评估四是否不等于六。如果两个语句都为真,代码将执行。
-- 不会运行if 2 + 2 == 6 and 4 ~= 6 thenprint("两个语句都为真")end-- 会运行if 4 + 2 == 6 and 4 ~= 6 thenprint("两个语句都为真")end
创建一个力量提升道具
力量提升道具是游戏内物品,能够给予玩家飞行、隐身或速度等特殊能力。这个力量提升道具将每次被触碰时提升玩家的行走速度。持续施加提升可能会使玩家移动得太快,因此将使用 and 来控制最高的行走速度限制。
设置力量提升道具
使用此代码与简单的部件或模型,例如水晶、硬币或发光的霓虹球。
创建一个名为 Powerup 的新部件,并插入一个名为 WalkSpeedManager 的脚本。
声明一个名为 speedBoost 的变量,并将脚本的父对象赋值给它。
-- 被触碰时给予暂时的速度提升local speedBoost = script.Parent设置一个名为 onTouch 的函数,并将其连接到父对象的 Touched 事件。然后进行游戏测试,以检查你的工作。
local speedBoost = script.Parentlocal function onTouch(otherPart)print("有东西触碰了 speedBoost")endspeedBoost.Touched:Connect(onTouch)WalkSpeed 属性位于 Humanoid 对象上。使用与创建陷阱部件相同的模式,创建一个检查 Humanoid 对象的条件。
查找 Humanoid 部件local function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid thenprint("找到了一个 Humanoid")endend
加速玩家
每次触碰速度提升道具时,速度提升将使角色行走得更快。这将会快速变得非常快。关键字 and 将确保玩家无法移动得过快,只有当玩家的速度低于某个值时,才启用速度提升。
如果找到了 Humanoid,获取当前的 WalkSpeed 值并加上 10。进行游戏测试,确保每次触碰速度提升道具时,角色会更快。
增加当前的 WalkSpeedlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid thenhumanoid.WalkSpeed += 10endendspeedBoost.Touched:Connect(onTouch)在 if 语句中,使用关键字 and 添加一个第二个条件,判断当前的 WalkSpeed 值是否小于 50。在添加提升后,最快的 WalkSpeed 值将是 60。
检查当前的 WalkSpeed 是否为 50 或更小if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10end
微调速度提升
每次速度提升道具被触碰时,都会调用 onTouch。每一步或最轻微的弹跳都会触发 Touched 事件并调用连接的函数。部件的属性 CanTouch 可以防止 Touched 事件触发。利用 CanTouch,每次激活后关闭速度提升一秒钟。
在施加提升后,将部件的 CanTouch 属性设置为 false。进行游戏测试,确保提升只应用一次。
禁用速度提升local speedBoost = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10speedBoost.CanTouch = falseendendspeedBoost.Touched:Connect(onTouch)使用 task.wait(1) 暂停脚本一秒钟,然后将 CanTouch 设置为 true。进行游戏测试,确保速度提升在一秒后可以重新施加。
完成的脚本local speedBoost = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")if humanoid and humanoid.WalkSpeed <= 50 thenhumanoid.WalkSpeed += 10speedBoost.CanTouch = falsetask.wait(1)speedBoost.CanTouch = trueendendspeedBoost.Touched:Connect(onTouch)在完成的脚本中尝试调整值。WalkSpeed 可以增加到 100。默认的 WalkSpeed 值是 16。
总结
关键字 and 可用于要求多个条件,然后再运行代码块,例如某个值大于 0 并且小于 100。或者如果存在 Humanoid,并且其 WalkSpeed 小于或等于 50。