patrykbajos
patrykbajos

Reputation: 393

How to make OpenGL camera moving in SFML by mouse move

I've good working (this may be important) FPS camera module in my "Game Engine". Now I'm using it with WASD and Up/Down/Left/Right. I want to add possibility to move camera by mouse. It's my code I've written:

if (event.type == sf::Event::MouseMoved)
{
    static glm::vec2 lastPos;
    glm::vec2 mousePos(event.mouseMove.x, event.mouseMove.y);
    glm::vec2 delta(lastPos - mousePos);
    delta *= -0.01;
    cam->addRotation(delta);

    sf::Vector2i center(parentWnd->getSFMLWindow()->getSize().x/2, parentWnd->getSFMLWindow()->getSize().y/2);
    lastPos.x = center.x;
    lastPos.y = center.y;

    sf::Mouse::setPosition(center, *parentWnd->getSFMLWindow());
}

How can I get moving my camera without cursor moving on the screen? It's working few seconds and camera locks (so I can't mouse move then I must kill process). I'd rather get event of mouse move not mouse position but SFML doesn't support that.

Upvotes: 2

Views: 1187

Answers (1)

patrykbajos
patrykbajos

Reputation: 393

I've solved this problem myself. Here's code:

if (event.type == sf::Event::MouseMoved) {
    static glm::vec2 lastMousePos;
    glm::vec2 mousePos(event.mouseMove.x, event.mouseMove.y);

    glm::vec2 deltaPos(mousePos - lastMousePos);
    const float mouseSensitivity = 0.1f;
    deltaPos *= mouseSensitivity;
    deltaPos.y *= -1;
    cam->addRotation(deltaPos);

    sf::Window const& sfWindow = *parentWnd->getSFMLWindow();
    auto windowSize = sfWindow.getSize();

    uint32_t maxMousePosRadius = glm::min(windowSize.x, windowSize.y) / 3;
    glm::vec2 windowCenter(windowSize.x / 2, windowSize.y / 2);

    if (glm::length(mousePos - windowCenter) > maxMousePosRadius) {
        sf::Mouse::setPosition(sf::Vector2i((int)windowCenter.x, (int)windowCenter.y), sfWindow);
        lastMousePos = windowCenter;
    }
    else {
        lastMousePos = mousePos;
    }
}

Upvotes: 3

Related Questions