Empty
Empty
Empty
CFrame (坐标系) 是 Roblox 中的一种数据类型,用于表示物体在三维空间中的位置和方向。通过了解如何创建和操作 CFrame,您可以精确控制游戏中部件和模型的放置和旋转。
位置 | 物体在三维世界中的位置。 |
方向 | 物体在三维世界中的旋转。 |
CFrame 示例
Empty
Empty
Empty
local myCFrame = CFrame.new(10, 5, -3)
Empty
Empty
Empty
local part = script.Parent
part.Position = Vector3.new(0, 5, 0)
-- Move the part to a new position using CFrame
part.CFrame = CFrame.new(10, 5, -10)
Roblox Studio
Empty
Empty
Empty
local part = script.Parent
part.Position = Vector3.new(0, 0.5, 0)
-- Rotate the part 45 degrees around the Y-axis
part.CFrame = CFrame.new(0, 0.5, 0) * CFrame.Angles(0, math.rad(45), 0)
Roblox Studio
Empty
Empty
Empty
local part = script.Parent
part.Position = Vector3.new(0, 0.5, 0)
-- Move the part to (10, 5, -3) and rotate it 45 degrees around the Y-axis
part.CFrame = CFrame.new(10, 5, -3) * CFrame.Angles(0, math.rad(45), 0)
Roblox Studio
Empty
Empty
Empty
local part = script.Parent
part.Position = Vector3.new(0, 2.5, 0)
-- Make the part look at the point (10, 2.5, -3)
local targetPosition = Vector3.new(10, 2.5, -3)
part.CFrame = CFrame.new(part.Position, targetPosition)
Roblox Studio
CFrame (世界空间与对象空间)
世界空间
WorldSpace 是指游戏世界的全局坐标系。
Empty
Empty
Empty
- 点的位置是相对于世界的固定原点定义的。
- 点的位置是相对于世界的固定原点定义的。
- 变换(如平移、旋转和缩放)是相对于世界的原点应用的。
- WorldSpace 中的坐标是绝对的,这意味着它们不受任何父对象或其他对象的位置或方向的影响。
对象空间
ObjectSpace,也称为本地空间,是相对于对象的坐标系。
Empty
Empty
Empty
- 点的位置是相对于对象的原点(而不是世界的原点)定义的。
- 点的位置是相对于对象的原点(而不是世界原点)定义的。
- 变换是相对于对象自己的坐标轴应用的,这些坐标轴可能与世界坐标轴相比已旋转和缩放。
- 这在处理层次结构中的子对象时特别有用,因为它们的变换基于其父对象的位置、方向和缩放。
Empty
Empty
Empty
-- Get a reference to the parent part
local parentPart = script.Parent
-- Function to create a child part and set its position using local CFrame
local function createChildPart()
-- Create the child part
local childPart = Instance.new("Part")
childPart.Size = Vector3.new(2, 2, 2)
childPart.Anchored = true
childPart.Parent = parentPart
childPart.Name = "Child"
-- Position the child part relative to the parent part using Local CFrame
local partCFrameLocal = CFrame.new(2, 2, 0) -- Local space offset
childPart.CFrame = parentPart.CFrame * partCFrameLocal -- Set the child part's CFrame
print("Child part created with Local Position:", partCFrameLocal.Position)
-- Print parent's world space position
print("Parent Part's World Position:", parentPart.CFrame.Position)
-- Demonstrating ToWorldSpace and ToObjectSpace
local modelCFrameWorld = parentPart.CFrame -- Parent's world CFrame
local partCFrameWorld = modelCFrameWorld:ToWorldSpace(partCFrameLocal)
print("World Position:", partCFrameWorld.Position) -- Prints the position of the part in world space
local recalculatedPartCFrameLocal = modelCFrameWorld:ToObjectSpace(partCFrameWorld)
print("Recalculated Local Position:", recalculatedPartCFrameLocal.Position) -- Should match partCFrameLocal.Position
end
-- Call the function to create the child part
createChildPart()
Roblox Studio