OpenGL sprite rotation to camera

Viewed 107

I am using OpenGL 3.3. It is necessary to make the sprite always look at the camera.

In most cases, the code is from the learnOpenGL lessons, I rework it to fit my needs. I tried in different ways, but so far I have not managed to do something that works adequately.

The projection is perspective.

glm::mat4 projection = glm::perspective(glm::radians(fov), (float)width_ / (float)height_, 0.1f, 30.0f);

I draw the sprite like this.

void SpriteRenderer3D::DrawSprite(const Texture2D& texture, glm::vec3 position, glm::vec3 camera_pos, glm::vec3 size, float rotate, glm::vec3 color) {
    // activate shader
    shader.Use();   
    // create transformations
    glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
    model = glm::translate(model, glm::vec3(position));  // first translate (transformations are: scale happens first, then rotation, and then final translation happens; reversed order)
    model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.5f * size.z)); // move origin of rotation to center of quad

    model = glm::rotate(model, glm::radians(rotate), glm::vec3(0.0f, 1.0f, 0.0f));
    model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, -0.5f * size.z)); // move origin back
    model = glm::scale(model, glm::vec3(size)); // last scale

    this->shader.SetMatrix4("model", model);
    // render textured quad
    this->shader.SetVector3f("spriteColor", color);     
    glActiveTexture(GL_TEXTURE0);
    texture.Bind(); 
}

I use this Vshader.

#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoords;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    TexCoords = vec2(aTexCoord.x, aTexCoord.y);
}

The view matrix is ​​considered this way when you move the camera.

glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
ResourceManager::GetShader("sprite3d").SetMatrix4("view", view);
0 Answers
Related