I am making a Fortnite style building system and I have an issue with my code that is responsible for calculating the position of the build.
Whenever the x-axis of the build position is supposed to get grid snapped to exactly zero, the Vector3 value instead contains a scientific notation number in the x-axis that is approximately equal to zero.
This issue allows builds to be placed on top of each other in certain spots since the code detects that the x-axis of the preview build and the existing build is different.
I am certain that this is an issue with the rotation being multipled onto the CFrame, but I have no idea how to fix this.
Here is an example of code that contains this behavior:
local BuildLocation = CFrame.new(0, 0, 0)
local BuildRotation = CFrame.Angles(0, math.rad(180), 0) -- Same issue with -180
local BuildOffset = CFrame.new(0, 0, 8.25)
local BuildCFrame = BuildLocation * BuildRotation * BuildOffset
print("Build Position: " .. tostring(BuildCFrame.Position))
The output:
Build Position: -7.212378818621801e-07, 0, -8.25
I was expecting the x-axis value to be exactly -0 here.
How can I add rotation to a CFrame without affecting the position value?
When doing maths on numbers, it’s not that uncommon for floating point inprecision to make a number ever so slightly different than what it is meant to be (the most famous case is 0.1 + 0.2 = 0.30000000004).
Instead of checking if 2 positions are identical, you could check that they are almost identical.
For vectors, you can check if they are almost identical like this:
local Vector1 = ...
local Vector2 = ...
if (Vector1 - Vector2).Magnitude < 1e-5 then
print("(Basically) identical")
else
print("Different")
end
or for single numbers:
local Num1 = ...
local Num2 = ...
if math.abs(Num1 - Num2) < 1e-5 then
print("(Almost) identical")
else
print("Different")
end