gpt4 book ai didi

c++ - SFML - 无法以正确的方向发射弹丸

转载 作者:行者123 更新时间:2023-11-28 02:34:21 24 4
gpt4 key购买 nike

我使用这段代码让怪物追逐玩家,效果很好:

float angle = atan2(player.y - monster.y, player.x - monster.x);
monster.move(cos(角度) * 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,禁用相机

最佳答案

问题是 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;
}

...

关于c++ - SFML - 无法以正确的方向发射弹丸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28026562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com