How to round all CFrame values?

In my games, the user can rotate objects only in 90-degree steps.
I use Tween to rotate the objects.
Tween almost always returns non-round values, due to the inaccuracy of float operations.
Therefore, a 90-degree rotation on the Y axis should return a clean Cframe like:

55 5 -20 -1 0 0 0 1 0 0 0 -1

But instead I get:

55 5 -20 -1 0 -1.5099580252809e-07 0 1 0 1.5099580252809e-07 0 -1

How to round all these CFrame values in a single step?

2 Likes

There’s not much you can do about floating point rounding errors, because it’s handled internally.
However, in Lua, integers can be represented in doubles accurately up to 2^53, so why not store the value(s) as an integer?

2 Likes

You can use math.floor to round down the values

How to reconstruct all CFrame values (x, y, z, R00, R01, R02, R10, R11, R12, R20, R21, R22)?

What do you mean? Get all of them?

I gave it a shot:

local cframeTable = table.pack(cframeValueHere:GetComponents())
for i, v in pairs(cframeTable) do
    cframeTable[i] = math.round(v)
end
local roundedCFrame = CFrame.new(table.unpack(cframeTable))
10 Likes

Perfect!
You should patent this solution… :sweat_smile:

Hello, is there a way to prevent this script from rounding one of the values ​​of a Cframe? Example, if it is coordinates, do not round the Y but round the others. Thanks!

Just use GetComponents to get all the components of the matrice, and round the ones you want.