简体   繁体   English

沿向量方向旋转矩阵?

[英]Rotating a matrix in the direction of a vector?

I have a player in the shape of a sphere that can move around freely in the directions x and z. 我有一个球形的播放器,可以在x和z方向上自由移动。 The players current speed is stored in a vector that is added to the players position on every frame: 玩家当前速度存储在矢量中,该矢量会添加到每一帧的玩家位置中:

m_position += m_speed;

I also have a rotation matrix that I'd like to rotate in the direction that the player's moving in (imagine how a ball would rotate if it rolled on the floor). 我还有一个旋转矩阵,我想按照玩家移动的方向旋转(想象一下,如果球在地板上滚动,球将如何旋转)。 Here's a short video to help visualise the problem: http://imgur.com/YrTG2al 这是一段简短的视频,可以帮助您直观地了解问题所在: http : //imgur.com/YrTG2al

Notice in the video when I start moving up and down (Z) as opposed to left and right (X) the rotation axis no longer matches the player's movement. 请注意,在视频中,当我开始上下移动(Z)而不是左右移动(X)时,旋转轴不再与玩家的移动相匹配。

Code used to produce the results: 用于产生结果的代码:

glm::vec3 UP = glm::vec3(0, 1, 0);
float rollSpeed = fabs(m_Speed.x + m_Speed.z);
if (rollSpeed > 0.0f) {
    m_RotationMatrix = glm::rotate(m_RotationMatrix, rollSpeed, glm::cross(UP, glm::normalize(m_Speed)));
}

Thankful for help 感谢帮助

Your rollSpeed computation is wrong -- eg, if the signs of m_Speed.x and m_Speed.z speed are different, they will subtract . 您的rollSpeed计算错误-例如,如果m_Speed.xm_Speed.z速度的符号不同,则它们将相减 You need to use the norm of the speed in the plane: 您需要在飞机上使用速度标准:

float rollSpeed = sqrt(m_Speed.x * m_Speed.x + m_Speed.y * m_Speed.y);

To be more general about it, you can re-use your cross product instead. 要更全面地讲,您可以重新使用交叉产品。 That way, your math is less likely to get out of sync -- something like: 这样,您的数学就不太可能不同步-类似于:

glm::vec3 rollAxis = glm::cross(UP, m_speed);
float rollSpeed = glm::length(rollAxis);
m_RotationMatrix = glm::rotate(m_RotationMatrix, rollSpeed, rollAxis);

rollSpeed should be the size of the speed vector. rollSpeed应该是速度向量的大小。

float rollSpeed = glm::length(m_Speed);

The matrix transform expects an angle. 矩阵变换期望一个角度。 The angle of rotation will depend on the size of your ball. 旋转角度将取决于您的球的大小。 But say it's radius r then the angle (in radians) you need is 但是说它是半径r那么你需要的角度(弧度)是

angle = rollSpeed/r;

If I understood correctly you need a matrix rotation which would work in any axis direction(x,y,z). 如果我正确理解,则需要可以在任何轴方向(x,y,z)上旋转的矩阵旋转。

I think you should write a rotate() method per axis (x, y, z), also you should point to direction on which axis your direction points, you should write direction.x or direction.y or direction.z and rotation matrix will understand to where the direction vector is being point. 我认为您应该为每个轴(x,y,z)写一个rotate()方法,还应该指向您的方向所指向的方向,应该编写direction.xdirection.ydirection.z以及旋转矩阵将了解方向向量指向的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM