3D orienting particles using velocity and position vectors in p5js

I’m currently writting a 3D implementation of the boids algorithm in P5.js but I’m having trouble orienting my boids according to their direction (velocity). I’m having a very hard time understand what rotation matrix would work so I tried a workaround with RotateZ and RotateY. The simplest solution that I feel should work goes along these lines :


rotateZ(atan2(this.vel.y, this.vel.x) + HALF_PI);
rotateY(atan2(this.vel.x, this.vel.z) + HALF_PI);

// Draw Boid Vertices..


But it doesn’t. (if you zoom in you can see that some triangles still face in the wrong direction)

I’ve written a much smaller version of the program which contains only the orientation for randomly generated particles that go in a single direction. It is available here directly on the p5js website : https://editor.p5js.org/itsKaspar/sketches/JvypSPGGh There is a default orbit control so you can zoom and drag the mouse to check the orientation of the particles.

I know I could use this.pos.add(this.vel.mag(10)) as the coordinate of the head of each particle but I dont want to as this will complicate things when I will try to add some wing animation to the model.

Thanks so much, I’ve been stuck on this for half a day now