0
Ch.2中的SFML游戏开发书。图4给出了当你通过两个方向(例如右和上)增加速度时,那么运动将比在一个方向上更快。Hallet 2D对角线运动的SFML游戏开发书
从研究中,我了解到,观察到的行为是,您将在同一时间段内达到对角线距离,就像您向左或向右或向上或向下移动一样。这是错误的,因为对角距离更长。
该书由SQRT除以2纠正此问题:
sf::Vector2f velocity = mPlayerAircraft->getVelocity();
// If moving diagonally, reduce velocity (to have always same velocity)
if (velocity.x != 0.f && velocity.y != 0.f)
mPlayerAircraft->setVelocity(velocity/std::sqrt(2.f));
从额外的研究,我发现,所述溶液可通过将速度的归一化矢量的速度相乘来实现。
velocity = mPlayerAircraft->getVelocity();
if (velocity.x != 0.f && velocity.y != 0.f) {
float velocityxsq = velocity.x * velocity.x;
float velocityysq = velocity.y * velocity.y;
float magnitude = std::sqrt(velocityxsq + velocityysq);
sf::Vector2f normalizedVector = velocity/magnitude;
velocity.x = velocity.x * std::abs(normalizedVector.x);
velocity.y = velocity.y * std::abs(normalizedVector.y);
mPlayerAircraft->setVelocity(velocity);
}
行为似乎是由两种实现,但归一化值正确并不总是1/SQRT(2)。唯一一次计算结果相同的情况是游戏开始时,我开始做对角线运动。如果我移动任何方向然后进行对角线移动,则数值会有所不同。
我做了规范化不正确吗? 为什么本书静态使用sqrt(2)?
太棒了,谢谢! –