Luís Jesus
Luís Jesus

Reputation: 1678

Rotate Over Own Axis

I'm trying to build a car and I'm starting with a polygon. The physics of the car is pretty much done however the car isn't facing the right position when it's steering.

So I tried using GLRotated with glRotated(_angle, 0, 0, 1); where _angle is the angle of the car in degrees but it's not rotating over it's own axis.

How can I fix this?

The code is here:

void Car::draw(){
    Vector2d min = _position - _size/2.0;
    Vector2d max = _position + _size/2.0;
    glColor3d(0.8, 0, 0);
    glLoadIdentity();
    glRotated(_angle, 0, 0, 1);
    glLineWidth(1.5);
    glBegin(GL_POLYGON);
        glVertex3d(min[0], min[1], 0);
        glVertex3d(max[0], min[1], 0);
        glVertex3d(max[0], max[1], 0);
        glVertex3d(min[0], max[1], 0);
    glEnd();
    glPopMatrix();
}

Thanks.

Upvotes: 2

Views: 338

Answers (1)

Tommy
Tommy

Reputation: 100652

glRotate* rotate around the origin. You can translate back to the origin, rotate and translate out again but you'd probably be best just not adding _position for yourself:

void Car::draw(){
    Vector2d min = - _size/2.0;
    Vector2d max = + _size/2.0;
    glColor3d(0.8, 0, 0);
    glLoadIdentity();
    glTranslated(_position[0], _position[1], 0);
    glRotated(_angle, 0, 0, 1);
    glLineWidth(1.5);
    glBegin(GL_POLYGON);
        glVertex3d(min[0], min[1], 0);
        glVertex3d(max[0], min[1], 0);
        glVertex3d(max[0], max[1], 0);
        glVertex3d(min[0], max[1], 0);
    glEnd();
    glPopMatrix();
}

That's the same as translate to origin, rotate, translate outward except starting with the object already on the origin. Also don't forget that OpenGL, like pretty much every graphics library, composes matrices so that you do the most local thing last, irrespective of how you might describe the total transform in the abstract.

Upvotes: 1

Related Questions