My snap to grid function is cancelling out rotation

Code
-- NewModel and NewBase is already defined

function SnapToGrid(NewModel, GridSize)
	local X = math.floor(NewBase.CFrame.X/GridSize + 0.5) * GridSize
	local Y = NewBase.CFrame.Y
	local Z = math.floor(NewBase.CFrame.Z/GridSize + 0.5) * GridSize
	NewModel:SetPrimaryPartCFrame(CFrame.new(X, Y, Z))
end

function Rotate()
	NewBase.CFrame = NewBase.CFrame * CFrame.Angles(0, math.rad(90), 0)
	NewModel:SetPrimaryPartCFrame(NewBase.CFrame)
	SnapToGrid(NewModel, 1)
end

Rotate()

I’m trying to get my furniture placement system to snap to the grid I define and take into account the rotation. It does this if I comment out SnapToGrid, but when I call SnapToGrid my rotation gets cancelled out.

With SnapToGrid commented out

With SnapToGrid

I have tried looking at other DevForum posts similar to this, but I wasn’t able to make sense of it and most of the furniture placement systems I found involved using the mouse, which my system doesn’t use.

Your snap to grid function is creating a vector components, and so when you create a CFrame out of the vector you’re essentially removing the LookAt argument. You should be reapplying the LookAt vector after snapping the object.

function SnapToGrid(NewModel, GridSize)
	local LookVector = NewBase.CFrame.LookVector
	local X = math.floor(NewBase.CFrame.X/GridSize + 0.5) * GridSize
	local Y = NewBase.CFrame.Y
	local Z = math.floor(NewBase.CFrame.Z/GridSize + 0.5) * GridSize
	NewModel:SetPrimaryPartCFrame(CFrame.new(X, Y, Z) * LookVector)
end

That’s giving me this error.

keep in mind I actually don’t know much about how cframe works :sob:

Whoops, that was my bad. I was trying to combine a CFrame and a vector. This should work better:

function SnapToGrid(NewModel, GridSize)
	local LookVector = NewBase.CFrame.LookVector
	local X = math.floor(NewBase.CFrame.X/GridSize + 0.5) * GridSize
	local Y = NewBase.CFrame.Y
	local Z = math.floor(NewBase.CFrame.Z/GridSize + 0.5) * GridSize
	NewModel:SetPrimaryPartCFrame(Vector3.new(X, Y, Z), Vector3.new(X, Y, Z) + LookVector)
end

Same error.

Oh man its been a long day. I forgot to actually make that a cframe.

NewModel:SetPrimaryPartCFrame(CFrame.new(Vector3.new(X, Y, Z), Vector3.new(X, Y, Z) + LookVector))
2 Likes