C++ 长方体顶点的点(按位与)

标签 c++ bit-manipulation bitwise-and

我试图在给定中心(Vector3)和沿 x、y 和 z 轴的边长的情况下计算长方体中的点。我在 math.stackexchange.com 上找到了以下内容:https://math.stackexchange.com/questions/107778/simplest-equation-for-drawing-a-cube-based-on-its-center-and-or-other-vertices它说我可以使用以下公式:

https://math.stackexchange.com/questions/107778/simplest-equation-for-drawing-a-cube-based-on-its-center-and-or-other-vertices World 类的构造函数是:

World::World(Vector3 o, float d1, float d2, float d3) : origin(o)
{
  // If we consider an edge length to be d, we need to find r such that
  // 2r = d in order to calculate the positions of each vertex in the world.
  float r1 = d1 / 2,
      r2 = d2 / 2,
      r3 = d3 / 2;

  for (int i = 0; i < 8; i++)
  {
    /* Sets up the vertices of the cube.
     *
     * @see http://bit.ly/1cc2RPG
     */
    float x = o.getX() + (std::pow(-1, i&1) * r1),
          y = o.getY() + (std::pow(-1, i&2) * r2),
          z = o.getZ() + (std::pow(-1, i&4) * r3);

    points[i] = Vector3(x, y, z);
    std::cout << points[i] << "\n";
  }
}

然后我将以下参数传递给构造函数:

Vector3 o(0, 0, 0);
World w(o, 100.f, 100.f, 100.f);

所有 8 个顶点的输出坐标是:

(50, 50, 50)
(-50, 50, 50)
(50, 50, 50)
(-50, 50, 50)
(50, 50, 50)
(-50, 50, 50)
(50, 50, 50)
(-50, 50, 50)

这不可能是正确的。非常感谢任何指导!

最佳答案

问题在于 pow 调用中的按位 &: 在 yz 组件中,它们总是分别返回 0 和 2 或 4。 -1^2 = -1^4 = 1,这就是为什么这些分量的符号总是正的。您可以尝试 (i&2)!=0(i&2) >> 1 作为 y 分量。 z 组件也是如此。

关于C++ 长方体顶点的点(按位与),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222035/

相关文章:

c - 仅使用小于 0xFF 的数字即可获取 0x55555555,|和<<

java - 如何在 Kotlin 中使用 Java 的位运算符?

整数上的 Java 按位 "&"

c++ - 如何在 C++ 中将类的实例与 char * 变量进行比较?

c++ - 递归最终数

c++ - 在 Windows C++ code::blocks 上 boost 正则表达式

c++ - 遍历 std::set 中包含的所有三重不同值?

lua - 如何将数字转换为有符号/无符号 16/32 位?

python-3.x - 如何翻转二进制表示中的位模式?

mysql - JPA @NamedQuery 以按位 AND (&) 作为条件