Gykonik Gykonik -4 years ago 141
C++ Question

Rotate 2D vector with glm proper

In a game I'm making, guns have a spread (float) and I want to give each bullet's angle a random value from range [-spread, spread]. For this I thought I could use

glm::rotate
, but the problem is that the bullets spread in almost every direction.

The code I use is:

void Gun::fire(const glm::vec2& direction, const glm::vec2& position, std::vector<Bullet>& bullets) {
static std::mt19937 randomEngine(time(nullptr));
// For offsetting the accuracy
std::uniform_real_distribution<float> randRotate(-_spread, _spread);


for (int i = 0; i < _bulletsPerShot; i++) {
// Add a new bullet
bullets.emplace_back(position,
glm::rotate(direction, randRotate(randomEngine)),
_bulletDamage,
_bulletSpeed);
}
}


(At the top I included
vector
and
glm/gtx/rotate_vector.hpp
)

Answer Source

I don't recall if GLM uses Radians or Degrees for calculating rotation, but 2 Radians is nearly a third of a full circle, which means that bullets will vary in direction by as much as 2 thirds of a whole circle. You may wish to test with smaller numbers, or else verify that GLM does indeed use Degrees to calculate rotation.

EDIT: In the most recent version of GLM, I looked through the source code. There's a commented out version of Rotate that explicitly converts Degrees to Radians, but the accessible source code has no such explicit conversion. So I'm left to presume that it is expecting Radians, not Degrees, as your inputs for Rotation.

GLM Source Code

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download