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

时间:2015-03-15 10:00:06

标签: c++ sfml

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
    }

对不起,如果这是最令人困惑的事情,但感谢您试图提供帮助。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

经过深思熟虑后:

变量:

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。

我希望我的评论可以弥补我在变量名称中的糟糕选择。