CFrame

CFrame (坐標系) 是 Roblox 中的一種數據類型,用於表示物體在三維空間中的位置和方向。通過了解如何創建和操作 CFrame,您可以精確控制遊戲中部件和模型的放置和旋轉。

位置物體在三維世界中的位置。
方向物體在三維世界中的旋轉。

CFrame 範例

local myCFrame = CFrame.new(10, 5, -3)
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)
Image 1
Roblox Studio
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)
Image 1
Roblox Studio
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)
Image 1
Roblox Studio
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)
Image 1
Roblox Studio

CFrame (世界空間與對象空間)

世界空間

WorldSpace 是指遊戲世界的全域坐標系。
  • 點的位置是相對於世界的固定原點定義的。
  • 點的位置是相對於世界的固定原點定義的。
  • 變換(如平移、旋轉和縮放)是相對於世界的原點應用的。
  • WorldSpace 中的坐標是絕對的,這意味著它們不受任何父對象或其他對象的位置或方向的影響。

對象空間

ObjectSpace,也稱為本地空間,是相對於對象的坐標系。
  • 點的位置是相對於對象的原點(而不是世界的原點)定義的。
  • 點的位置是相對於對象的原點(而不是世界原點)定義的。
  • 變換是相對於對象自己的坐標軸應用的,這些坐標軸可能與世界坐標軸相比已旋轉和縮放。
  • 這在處理層次結構中的子對象時特別有用,因為它們的變換基於其父對象的位置、方向和縮放。
-- 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()
Image 1
Roblox Studio

如果你覺得這個教程對你有幫助,並且願意支持我的工作,請考慮請我飲杯咖啡。

非常感謝你的支持!

請我飲杯咖啡