【问题标题】:SFML - can't get the projectile shooting in the right directionSFML - 无法将弹丸射向正确的方向
【发布时间】:2023-03-30 19:25:02
【问题描述】:

我用这段代码来追逐玩家,这很好用:

float angle = atan2(player.y - monster.y, player.x - monster.x); monster.move(cos(angle) * 0.5f,0); monster.move(0, sin(angle) * 0.5f);

我想我会改变它,以便子弹从玩家射到鼠标指针:

float angleShot2 = 0.0f;

...

case sf::Event::MouseButtonReleased:
        {
         projectile.setPosition(player.x,player.y);
         float angleShot = atan2(sf::Mouse::getPosition(window).y - projectile.y, 
                                 sf::Mouse::getPosition(window).x - projectile.x );
         angleShot2 = angleShot;  //so it goes in a straight line
        }

...

 projectile.move(cos(angleShot2) * 1.0f, 0);
 projectile.move(0, sin(angleShot2) * 1.0f);

玩家、怪物和子弹都是矩形

窗口分辨率为 1280x900

设置玩家位置后,我使用相机跟随玩家的方式

sf::View view2(sf::FloatRect(0, 0, 1280, 900));
view.setSize(sf::Vector2f(1280, 900)); 
window.setView(view);

...

view.setCenter(player.getPosition());

子弹不会去鼠标释放的地方并且会朝着奇怪的方向前进,也许你对我的代码有一些提示或制作子弹的不同方法。实在是想不出什么了…… 我尝试将 y 的 cos 和 x 的 sin 反转,禁用相机

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    问题是 sf::Mouse::getPosition 返回光标在窗口坐标中的位置,而所有实体都使用世界坐标。您可以使用 sf::RenderWindow 对象的 mapPixelToCoords 成员函数来解决此问题:

    ...
    case sf::Event::MouseButtonReleased:
    {
         projectile.setPosition(player.x,player.y);
         sf::Vector2f mousePosition = window.mapPixelToCoords(sf::Mouse::getPosition(window));
         float angleShot = atan2(mousePosition.y - projectile.y, 
                                 mousePosition.x - projectile.x );
         angleShot2 = angleShot;  
    }
    
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多