【发布时间】:2015-04-06 09:44:54
【问题描述】:
问题有点变化,我想出了如何绕单轴旋转
我想使用一个角度围绕 Y 轴旋转一个框。 这个盒子有一个大小,还有一个 Vector3f 来表示旋转。
要正确旋转盒子,我要做的是旋转原点位置,然后旋转原点位置加上大小,然后使用这两个参考来渲染盒子。
但是,这种旋转无法正常工作并导致渲染伪影。
这是我旋转位置的代码:
Matrix4f matrix = new Matrix4f();
// Rotate the origin position
Vector3f pos = new Vector3f(new Vector3f(blockX, blockY, blockZ));
matrix.m03 = pos.x;
matrix.m13 = pos.y;
matrix.m23 = pos.z;
Vector3f rot = new Vector3f(new Vector3f(0, 1f, 0f));
Matrix4f.rotate((float) Math.toRadians(45f), rot, matrix, matrix);
Vector3f locationMin = new Vector3f(matrix.m03, matrix.m13, matrix.m23);
// Rotate the position with the size
// Top left back is the position of the block
Vector3f sizeRot = new Vector3f(new Vector3f(blockX + size, blockY + size, blockZ + size));
matrix = new Matrix4f();
matrix.m03 = sizeRot.x;
matrix.m13 = sizeRot.y;
matrix.m23 = sizeRot.z;
rot = new Vector3f(new Vector3f(0, 1f, 0f));
Matrix4f.rotate((float) Math.toRadians(45f), rot, matrix, matrix);
Vector3f locationMax = new Vector3f(matrix.m03, matrix.m13, matrix.m23);
// Then here I use the locationMax and the locationMin to render the cube
这段代码可能有什么问题?我用来旋转盒子的逻辑是否正确?如旋转原点位置然后旋转原点位置加上大小..
编辑:我发布了翻译后旋转是愚蠢的,所以我只是旋转了未翻译的 locationMax(它只是大小),然后我翻译了,我仍然得到相同的结果(图形人工制品)。
新代码:
float rx = blockX, ry = blockY, rz = blockZ;
Matrix4f matrix = new Matrix4f();
Vector3f rot = new Vector3f(0, 1f, 0f);
matrix = new Matrix4f();
matrix.m03 = size;
matrix.m13 = size;
matrix.m23 = size;
Matrix4f.rotate((float) Math.toRadians(45f), rot, matrix, matrix);
matrix.translate(new Vector3f(rx, ry, rz), matrix);
float mx = matrix.m03;
float my = matrix.m13;
float mz = matrix.m23;
// Here is use rx, ry, rz and mx, my, mz to render the box
============ * 我想通了(见下文)* =============
编辑:
这就是我最终做的:
// Origin point
Vector4f a = new Vector4f(blockX, blockY, blockZ, 1);
// Rotate a matrix 45 degrees
Matrix4f mat = new Matrix4f();
mat.rotate((float) Math.toRandians(45f), new Vector3f(
0, 1f, 0), mat);
/* Transform the matrix to each point */
Vector4f c = new Vector4f(size.x, 0, size.z, 1);
Matrix4f.transform(mat, c, c);
Vector4f.add(c, a, c);
Vector4f b = new Vector4f(size.x, 0, 0, 1);
Matrix4f.transform(mat, b, b);
Vector4f.add(b, a, b);
Vector4f d = new Vector4f(0, 0, size.z, 1);
Matrix4f.transform(mat, d, d);
Vector4f.add(d, a, d);
// Here is use a, b, c, and d to render the box.
这个问题是我想围绕所有轴旋转,而不仅仅是围绕 Y 轴。这使得代码非常长且不可读,并且当我尝试围绕所有轴旋转时会出现很多错误。
更新问题:
如何获取上述代码并制作它,以便我可以围绕所有 3 个轴旋转。我想这样做,这样我就可以拥有一个始终面向相机的广告牌。
这是我计算相机和物体之间角度的方法:
Vector3f angle = new Vector3f();
// Calculate the distance between camera and object
Vector3f.sub(game.getCamera().getLocation(),
new Vector3f(blockX, blockY, blockZ), angle);
// Calculate the angle around the Y axis.
float vectorAngle = (float) ((float) Math.atan2(angle.z, angle.x) * -1 + (Math.PI / 2.0f));
【问题讨论】:
-
这是 toRadians 而不是 toRandians :)
标签: java opengl matrix vector rotation