Quick and easy rotation of Vector2?

I’m using nalgebra in amethyst. I just want to apply a rotation to a unit vector by some angle. I am aware that I can create a new rotation matrix and apply it. But I’m doing this every frame and I really don’t want to have to build up a new rotation matrix for every entity for every frame. There really ought to be an easy rotate function like there is in glm, no? I’ve been reading the docs for ages and can’t seem to find anything like this.

Hi!

Creating a Rotation2 matrix (or an UnitComplex) then multiplying your vector by it will be exactly as efficient as doing the computations manually without creating the intermediate rotation object.

If you are referring to that function from the C++ GLM, you can see that:

T const Cos(cos(angle));
T const Sin(sin(angle));

Result.x = v.x * Cos - v.y * Sin;
Result.y = v.x * Sin + v.y * Cos;

Is just the hand-written version of:

use nalgebra::UnitComplex;
UnitComplex::new(angle) * v

Both versions will compute one cos, one sin and do exactly the same arithmetic operations.

Though if what you want is just a simpler API that does not require you to deal with UnitComplex explicitly, you can use the nalgebra-glm crate which has mostly the same functions as the C++ GLM. In particular, you need nalgebra_glm::rotate_vec2.

1 Like

Thanks! I understand now that nalgebra is more of a general purpose linear algebra library than a CG library, so it’s understandable that this would work this way. Nalgebra-glm looks good for my purpose but unfortunately amethyst doesn’t use it and I don’t want to install two nalgebra crates.

Nalgebra-glm looks good for my purpose but unfortunately amethyst doesn’t use it and I don’t want to install two nalgebra crates.

Using nalgebra-glm won’t install two nalgebra crates. nalgebra-glm will automatically use the same nalgebra dependency as amethyst.