プレイヤーの健康を減少させるトラップは、条件文を使ってコーディングできる楽しいゲームプレイ要素です。タッチされたときにプレイヤーの健康をゼロにするパーツを作成して、条件文の練習をしましょう。
トラップの設定
トラップは、オビーのような動きに基づくチャレンジがあるゲームで非常に効果的です。これらのステップでは、必要な変数と関数を設定します。まずはコードボックスを見ずにできるだけ多くのことを行ってください。
トラップパーツを作成し、名前を付けます。パーツにスクリプトを挿入します。
スクリプト内に説明的なコメントを追加し、スクリプトの親を参照するための変数を使用します。
-- プレイヤーがこのパーツに触れたら、健康を0に設定するlocal trapPart = script.ParentonTouch()という名前の関数を作成し、otherPartという名前のパラメータを設定します。
-- プレイヤーがこのパーツに触れたら、健康を0に設定するlocal 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のHealthをゼロに設定します。
Humanoidがlocal humanoidに正常に割り当てられたかどうかを確認するためにif文を使用します。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- Humanoidが見つかったかどうかを評価if humanoid thenendendtrapPart.Touched:Connect(onTouch)print文を追加し、これまでのコードを確認します。
local trapPart = script.Parentlocal function onTouch(otherPart)local character = otherPart.Parentlocal humanoid = character:FindFirstChildWhichIsA("Humanoid")-- Humanoidが見つかったかどうかを評価if 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")-- Humanoidが見つかったかどうかを評価if humanoid thenprint("Humanoidが見つかりました")humanoid.Health = 0endendtrapPart.Touched:Connect(onTouch)トラップをテストします。
まとめ
このトラップパーツは、条件文を使用してHumanoidパーツを検出し、Humanoidの健康をゼロに設定しました。このスクリプトは、触れたオブジェクトを問わず破壊してしまう以前のトラップスクリプトの改善版です。
ただし、いくつかの欠点もあります。Humanoidはプレイヤーだけでなく、非プレイ可能なキャラクターにも存在します。このスクリプトは、プレイヤーの健康をゼロに設定するのにしか適していません。少しの健康を減らすことを試みることもできますが、望ましいよりも早く健康を減らしてしまう可能性があります。後のレッスンでは、プレイヤーからどれだけの健康を減らすかをより制御するためのさらなる改善が提供されます。