2015 年 11 月の更新:
PrimaryPart の使用
この記事を書いてから、ROBLOX は API に関して多くの変更を行いました。要求どおりにモデルを移動するには、モデルの PrimaryPart プロパティをモデル内の中央部分に設定する必要があります。これはorigin
、モデルの動きの として機能します。
model:SetPrimaryPartCFrame(cframe)
その後、モデルの CFrame を設定するために使用できます。を使用してこのプロパティを取得することもできますが、これmodel:GetPrimaryPartCFrame()
は のショートカット メソッドに過ぎないと思いますmodel.PrimaryPart.CFrame
。
コードでは、次のようになります。
-- Set PrimaryPart:
MODEL.PrimaryPart = MODEL.SomeCentralPart
...
-- CFrame movement:
local movement = CFrame.new(0, 10, 0)
-- Move the model:
MODEL:SetPrimaryPartCFrame(MODEL:GetPrimaryPartCFrame() * movement)
オプション A: モデルのメソッドを使用する
あなたはこれを必要以上に難しくしていると思います。このような問題が発生した場合は、提供されている現在の API を確認してください。ROBLOX Model オブジェクトには、モデルを変換するために Vector3 引数を取る「TranslateBy」と呼ばれる気の利いたメソッドが含まれています。
使用MODEL:TranslateBy(Vector3)
は、衝突を無視するため、CFrame を介してモデルを移動するのと似ています。
もう 1 つの方法はMODEL:MoveTo(Vector3)
、モデル全体を特定の Vector3 ワールド位置に移動することです。これの欠点は、衝突することです。
同じ MoveTo 効果を衝突なしで取得する 1 つの方法は、TranslateBy メソッドを使用して実行できます。
MODEL:TranslateBy(Vector3Position - MODEL:GetModelCFrame().p)
オプション B: モデルの CFrame を操作するカスタム関数を作成する
もう 1 つの方法は、モデル全体の CFrame を完全に操作することです。これを行うには、モデル全体を「原点」に対して相対的に移動させる巧妙な関数を作成できます。これは、3 次元を除いて、点と原点を指定してグリッド上で形状を移動するのと似ています。ただし、ROBLOX の組み込み関数を使用すると、これははるかに簡単になります。
これを行う良い方法は、モデル全体に CFrame 値を実際に割り当てることができる関数を作成することです。別の方法は、CFrame を介した翻訳も許可することです。
次に例を示します。
function ModelCFrameAPI(model)
local parts = {} -- Hold all BasePart objects
local cf = {} -- API for CFrame manipulation
do
-- Recurse to get all parts:
local function Scan(parent)
for k,v in pairs(parent:GetChildren()) do
if (v:IsA("BasePart")) then
table.insert(parts, v)
end
Scan(v)
end
end
Scan(model)
end
-- Set the model's CFrame
-- NOTE: 'GetModelCFrame()' will return the model's CFrame
-- based on the given PrimaryPart. If no PrimaryPart is provided
-- (which by default is true), ROBLOX will try to determine
-- the center CFrame of the model and return that.
function cf:SetCFrame(cf)
local originInverse = model:GetModelCFrame():inverse()
for _,v in pairs(parts) do
v.CFrame = (cf * (originInverse * v.CFrame))
end
end
-- Translate the model's CFrame
function cf:TranslateCFrame(deltaCf)
local cf = (model:GetModelCFrame() * deltaCf)
self:SetCFrame(cf)
end
return cf
end
-- Usage:
local myModel = game.Workspace.SOME_MODEL
local myModelCF = ModelCFrameAPI(myModel)
-- Move to 10,10,10 and rotate Y-axis by 180 degrees:
myModelCF:SetCFrame(CFrame.new(10, 10, 10) * CFrame.Angles(0, math.pi, 0))
-- Translate by 30,0,-10 and rotate Y-axis by 90 degrees
myModelCF:TranslateCFrame(CFrame.new(30, 0, -10) * CFrame.Angles(0, math.pi/2, 0))