让精灵跟随鼠标,使用视图时出现奇怪的故障

Getting sprite to follow mouse, weird glitch when using views

本文关键字:故障 视图 跟随 精灵 鼠标      更新时间:2023-10-16

我想知道是否有人可以帮助我。我的精灵一直跟随我的鼠标,直到我开始使用视图,我才开始使用SFML,使精灵跟随我的播放器,我使用这个。

void player::rotateToMouse(sf::Sprite &sprite, sf::RenderWindow &window)
{       
    this->mouse = sf::Mouse::getPosition(window);

    const float PI = 3.14159265;
    float a = playerPosition.x - mouse.x;
    float b = playerPosition.y - mouse.y;
    mouseAngle = (atan2(b, a)) * 180 / PI; 
    playerSprite.setRotation(mouseAngle + 180);
}

我将这段代码添加到我的更新方法中,像这样,

void player::update(sf::RenderWindow &window){

    this->rotateToMouse(playerSprite, window);
    this->followPlayer();

我这样设置我的视图,

void player::followPlayer(){
    view.reset(sf::FloatRect(0, 0, 32 + 10, 32 + 10));

    view.zoom(15);

    view.setCenter(playerSprite.getPosition());
}

我的移动代码是,

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
    playerSprite.move(std::cos(3.14159265 * mouseAngle / 180.f)  * speed  *-1, std::sin(3.14159265 * mouseAngle / 180.f) * speed  *-1);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)){                              //Speed
    playerSprite.move(std::cos(3.14159265 * mouseAngle / 180.f)  * speed , std::sin(3.14159265 * mouseAngle / 180.f)  * speed );
}
this->playerPosition = playerSprite.getPosition();

我可以看到精灵的面稍微偏离,过了一会儿他开始随机旋转,我是c++的新手,如果有人能帮助我,我将不胜感激。

您需要使用sf::RenderTarget::mapPixelToCoords。基本上,你需要改变计算鼠标位置的方式:

this->mouse = sf::Mouse::getPosition(window);

this->mouse = window.mapPixelToCoords(sf::Mouse::getPosition(window));