チャプター 2

Step 02

ボールを何個も自動的に作るコードを書いてみる!

ボールをランダムに、何個も作成する

今度はボールがランダムな場所に何個も作られるようにします。
次のコードをコピペして使ってください。
-- ランダムな座標を生成する関数
local function getRandomPosition()
local x = math.random(-50, 50)
local y = math.random(5, 8) -- 地面から少し浮かせるため
local z = math.random(-50, 50)
return Vector3.new(x, y, z)
end

-- 球体を生成する関数
local function createBall()
local ball = Instance.new("Part")
ball.Name = "FireBall"
ball.Shape = Enum.PartType.Ball
ball.Size = Vector3.new(5, 5, 5) --玉の大きさ
ball.Position = getRandomPosition()
ball.Anchored = true
ball.CanCollide = true;
ball.Parent = game:GetService("Workspace")
end

-- 1秒に2個玉を生成する
while true do
createBall()
wait(0.5) -- 0.5秒ごとに新しい球体を生成
end
次にすすむ