【问题标题】:How to place part on top of the terrain in Roblox?如何在 Roblox 的地形上放置零件?
【发布时间】:2020-02-12 15:21:36
【问题描述】:

我在我的 ROBLOX 游戏中生成了一个地形(山丘、平原、河流),并且我有一个树模型。树只是一组“砖块”,所以它看起来有点像 Minecraft 树。

现在我想在运行时以编程方式克隆该树,我需要将该副本(克隆)放在地图上的其他位置。

这一切都很容易。但是在我给我的克隆新坐标后(我保持 Y 轴的坐标与我的原始树相同),它被放置在或在空中,或者它在我的地形表面下

如何将它直接放置在地形上? 或者如何获取地图上特定地点的 Y 轴坐标?

谢谢!

编辑

虽然@Kylaaa 的回答非常完整,但我在这里提供了我的解决方案,同时我还需要有关该地方地形材料的信息(岩石/草/等)

function FindTerrainHeight(pos)

local VOXEL_SIZE = 4
local voxelPos = workspace.Terrain:WorldToCell(pos)

// my region will start at -100 under the desired position and end in +100 above desired position
local voxelRegion = Region3.new((voxelPos - Vector3.new(0,100,0)) * VOXEL_SIZE, (voxelPos + Vector3.new(1,100,1)) * VOXEL_SIZE)
local materialMap, occupancyMap = workspace.Terrain:ReadVoxels(voxelRegion, VOXEL_SIZE)

local steps = materialMap.Size.Y // this is actually 200 = height of the region

// now going from the very top of the region downwards and checking the terrain material
// (while it's AIR = no terrain found yet)
for i = steps, 1, -1 do

    if (materialMap[1][i][1] ~= Enum.Material.Air) then

        materialMap[1][i][1] ---> this is the material found on surface
        ((i-100) * VOXEL_SIZE) ---> this is the Y coordinate of the surface in world coordinates
    end
end

return false
end

编辑 2

所以事实证明@Kylaaa 的回答解决了所有问题。它还包括地形材料!作为元组中的第 4 项。这意味着我的解决方案太复杂了,没有理由。使用他的解决方案。

【问题讨论】:

    标签: roblox


    【解决方案1】:

    尝试从起点向下投射光线,直到找到地形。 game.Workspace:FindPartOnRayWithWhitelist() 非常适合这个!

    -- choose some starting point in world space
    local xPos = 15
    local yPos = 20
    local zPos = 30
    
    -- make a ray and point it downward.
    -- NOTE - It's unusual, but you must specify a magnitude for the ray
    local origin = Vector3.new(xPos, yPos, zPos)
    local direction = Vector3.new(0, -100000, 0)
    local ray = Ray.new(origin, direction)
    
    -- search for the collision point with the terrain
    local whitelist = { game.Workspace.Terrain }
    local ignoreWater = true
    local _, intersection, surfaceNormal, surfaceMaterial = game.Workspace:FindPartOnRayWithWhitelist(ray, whitelist, ignoreWater)
    
    -- spawn a part at the intersection.
    local p = Instance.new("Part")
    p.Anchored = true
    p.Size = Vector3.new(1, 1, 1)
    p.Position = intersection -- <---- this Vector3 is the intersection point with the terrain
    p.Parent = game.Workspace
    

    如果您调用 SetPrimaryPartCFrame() 时您的模型以不寻常的方式移动,请注意 Roblox 物理学不喜欢相互穿透的对象。因此,模型通常会被向上推,直到它们不再相互渗透。 CanCollide = false 的对象不会出现此问题,但如果它们不是 Anchored 或焊接到零件设置为 CanCollide = true,它们也会从世界中消失。

    【讨论】:

    • 超级、完整、清晰的答案。谢谢!我还将发布我的解决方案,同时我还需要有关该地点地形类型的信息(岩石/草/泥)
    • 'FindPartOnRayWithWhitelist()' 还将材料作为元组中的第 4 项返回。我没有将它包含在我的示例中,因为我认为它会使答案变得混乱。
    猜你喜欢
    • 2018-12-28
    • 2021-12-04
    • 2018-09-14
    • 2022-08-19
    • 2021-10-22
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多