简体   繁体   中英

How to draw a 3D vector in OpenGL?

I'm making a 3D simulation of the motion of particles, and I want to draw arrows representing the electric field at certain positions. I made an arrow mesh in Blender and exported it as a .obj so I can use it in my code (I made a .obj loader), but I can't seem to rotate it properly so that it points in the right direction, even though I checked that the electric field vector was calculated properly. I am getting some weird results as well. For example, if the vector should be pointing upwards, it points downwards, but when I comment out the code that rotates in the x axis, the arrow points downwards like intended. Then if it's supposed to point to the right, it points inwards (towards negative z axis), but when I comment out the rotation in the y axis, it points to the right.

Here's my code for rotation and rendering of the arrows:

void Render(Vector3 cameraPos)
{
    glScalef(field.length() * ArrowLength,1.0,1.0);
    glTranslatef(0,0,_zdefault);
    glRotatef(Entity::yangle,0,1,0);
    glTranslatef(pos.getX() + cameraPos.getX(), pos.getY() + cameraPos.getY(), pos.getZ() + cameraPos.getZ() - _zdefault);

    glRotatef(atan2(field.getZ(),field.getY()) * 180/M_PI, 1.0,0.0,0.0);
    glRotatef(atan2(field.getX(),field.getZ()) * 180/M_PI, 0.0,1.0,0.0);
    glRotatef(atan2(field.getY(),field.getX()) * 180/M_PI, 0.0,0.0,1.0);

    glBindTexture(GL_TEXTURE_2D,arrowTexture);

    glCallList(arrow);
    glLoadIdentity();
};

field is the Vector that represents the electric field. The lines

glTranslatef(0,0,_zdefault);
glRotatef(Entity::yangle,0,1,0);

Are there so that I can rotate the entire scene, kind of like orbiting around it in Blender. Also, Vector3 is just a simple Vector class that I wrote with very basic functionality. Like I said though, there is no problem with the vector calculations, I checked that, I just can't use the Vectors to rotate things properly.

I have a feeling my angles are a little screwed up for the glRotatef's where I use atan2, but I still can't understand how that would affect the rotations as described before.

Is there any way to rotate something based only on vector components?

first you should probably not use the glRotatef glTranslatef etc. legacy pipeline and use shaders and manage your own matrices instead.

Besides that it's better to use a lookAt transformation using the field as your direction direction and some up as the up vector

For rotating the entire scene you just define a center and rotate all vectors around that with the same transformation after you translate them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM