我编写了一个 Plugin 脚本,它从“ReplicatedStorage/Trees”中随机选择一个树模型,然后克隆它并将其放置在 3D 世界中的点击点(在 Roblox Studio 编辑器中,而不是在游戏中)。
问题似乎是树木没有直立——在我展示的视频中,即使在平坦的地形上,树木也不会直(向上)克隆。我试过了:
将 CFrame 角度设置为 0、90 或 180 等(我检查了所有轴),但树仍然没有向上旋转...
local rotation = CFrame.Angles(math.rad(0), math.rad(0), math.rad(0))
SpawnedTree:PivotTo(position * rotation)
只需设置位置:
SpawnedTree:PivotTo(position)
AND!我使用名为Pine Tree的树模型 - 枢轴位于正确的位置,方向和位置设置为
(0, 0, 0)
。
整个脚本(不是本地脚本)位于
workspace
,没有 GUI 代码:
local NO_TREES_FOUND_ERROR = "No trees found!"
local NO_TREES_FOLDER_FOUND_ERROR = "No 'Trees' folder found!"
-- Tag Log
local TAG = "TPlace: "
-- Spawn tree
local function spawnTree(position)
local treeToSpawn = nil -- Final Tree Model to spawn
local randomInt -- Number of model to pick
local storage = game:GetService("ReplicatedStorage") -- Obvious
if not storage:FindFirstChild("Trees") then -- Just check if 'Trees' folder exist
showError(NO_TREES_FOUND_ERROR) -- In GUI
warn(TAG .. "No 'Trees' folder found! Create this folder in ReplicatedStorage and place trees there!")
else
local children = storage.Trees:GetChildren()
if #children == 0 then -- If 'Trees' folder exist, check if there is tree models
showError(NO_TREES_FOUND_ERROR) -- In GUI
warn(TAG .. "No trees found! They need to be in ReplicatedStorage/Trees")
else
if #children == 1 then -- If there is only one model, select '1'
randomInt = 1
else
local randomInt = math.random(1, #children)
end
treeToSpawn = children[randomInt]
local SpawnedTree = treeToSpawn:Clone() -- Clone Tree
SpawnedTree.Parent = workspace -- Add to workspace
local rotation = CFrame.Angles(math.rad(0), math.rad(0), math.rad(0))
-- Set rotation (does'nt work)
SpawnedTree:PivotTo(position * rotation) -- Transform
end
end
end
-- Get Mouse click positions
local Mouse = plugin:GetMouse()
local target = nil
local function button1Down()
target = Mouse.Target
end
local function button1Up()
if target == Mouse.Target and target.Name == "Terrain" then
spawnTree(Mouse.Hit)
end
end
local ClickEventDown
local ClickEventUp
ClickEventDown = Mouse.Button1Down:Connect(button1Down)
ClickEventUp = Mouse.Button1Up:Connect(button1Up)
plugin:Activate(isConnected)
需要注意的是 Mouse.Hit 对象是 CFrame,而不是 Vector3。这意味着它带有位置和旋转信息。根据文档:
Hit CFrame 的方向与 Mouse.UnitRay 的方向相对应。
这意味着 y 轴可能不是笔直向上的,而是基于相机位置和鼠标位置。
因此,如果您想去掉旋转信息,可以使用 CFrame 的
.p
或 .Position
属性来仅获取位置信息。
所以试试这个:
local function button1Up()
if target == Mouse.Target and target.Name == "Terrain" then
spawnTree(Mouse.Hit.Position)
end
end