当我按下按钮时,向鼠标方向的精灵添加速度

Add velocity to a sprite in the direction of the mouse, when i push a button

float avx = 20;//avatar x coordinate
float avy = 20;//avatar y coordinate
float avd = 0;//avatar rotation degree

我有它所以精灵在鼠标的方向上倾斜(avd)。

sf::Vector2f av = avatar.getPosition();
    sf::Vector2i m = sf::Mouse::getPosition(window);
    sx = m.x - av.x;
    sy = m.y - av.y;
    avd = (atan2(sy, sx)) * 180 / pi + 90;
    avatar.setRotation(avd);

我需要适当的 x(x 速度) 和 y(y 速度) 值来添加到整体 x(avx) 和 y(avy) 坐标中。基本上就像给火箭增加前进动力。

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
    {
        //accelerate toward angle "avd" toward mouse
        //what i can't figure out
    }

抱歉,如果这是有史以来最令人困惑的事情,但感谢您的帮助。

X 轴加速 sin(avd)*speed,Y 轴加速 cos(avd)*speed

深思熟虑:

变量:

sf::Vector2f av = avatar.getPosition();//avatar x(av.x) & y(av.y) coords 
sf::Vector2i m = sf::Mouse::getPosition(window);//mouse x(m.x) & y(m.y) coords
float avx = 20;//avatar x coordinate
float avy = 20;//avatar y coordinate
float dx = 0;//x directional fraction
float dy = 0;//y direction fraction 
float dx2 = 0;//x speed
float dy2 = 0;//y speed
float h = 0;//hypotenuse
const float speed = 8; //constant for acceleration(larger the slower)

正在使用:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))//if W is being pushed
    {
        dx = av.x - m.x;//mouse & av x distance
        dy = av.y - m.y;//mouse & av y distance

        h = sqrt((dx*dx) + (dy*dy));//absolout distance of mouse & av

        dx /= h;//% of hypotenuse that is x
        dy /= h;//% of hypotenuse that is y

        dx /= speed;//% of const speed that x gets
        dy /= speed;//% of const speed that y gets

        dx2 += dx;//x acceleration
        dy2 += dy;//y acceleration
    }
    avx -= dx2;//x momentum
    avy -= dy2;//y momentum

可以通过操纵 dx2 和 dy2 来达到制动或最大速度。

我希望我的评论能弥补我在变量名方面的错误选择。