Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
How to set forward direction using lookAt matrix?

I have a WebGL 3D scene set up with a single mesh and a camera. I can translate/rotate both correctly (it appears so in testing, anyway).

Now I would like to be able to set the 'forward' direction of my mesh's transform.

Without much of a clue, I have tried this:

// _value being a 3-component direction such as [ 0, 0, 1 ]
// V4.up being the world up vector: [ 0, 1, 0 ]
set forward(_value) {

    const p = V4.add(this.position, _value);
    const m = M4.lookAt(this.position, p, V4.up);
    this.rotation = M4.transform(m, this.rotation);
}

When the mesh is at [ 0, 0, 0 ] (origin), this appears to do nothing. When the mesh is not at the origin, it spins rapidly on all three axis with increasing speed as I move away from the origin.

EDIT: I realized I was passing a direction vector to .lookAt. I've now altered the above method to turn that direction into a position (p), offset from the transform's position. However this still results in the same spinning issue as before.

My lookAt matrix looks like this;

lookAt(_from, _to, _up) {

    const fwd = V4.normalize(V4.sub(_from, _to));
    const right = V4.cross(_up, fwd);

    return [

        right[0], right[1], right[2], 0,
        _up[0], _up[1], _up[2], 0,
        fwd[0], fwd[1], fwd[2], 0,
        _from[0], _from[1], _from[2], 1
    ];
}

(I am currently using the inverse of this lookAt matrix to get (seemingly) correct camera'd rendering.)

In my shader, I set gl_Position like so;

void main() {

    gl_Position = projectionMatrix * viewMatrix * worldMatrix * vertexPosition;
}

In my Transform class, I can get the forward direction like so;

get forward() {
        
    return V4.normalize(M4.transform(M4.rotate(this.rotation), V4.forward));
}

Note; V4 is my vector4 operations class. M4 is my matrix operations class. Note; V4.forward = [ 0, 0, 1 ];

EDIT 2: I have now tried using glMatrix instead of my own M4 class to see if there were problems with mine. I get the exact same results with both.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!