算法沿直线运动算法、直线

2023-09-11 06:10:57 作者:梦里有星星

我有一个函数如下:

bool Action::approach (img_comp &mover, sf::Vector2f start, sf::Vector2f end, int speed)
{
    //Get the change in x and y
    float delta_x = (end.x - start.x) / speed;
    float delta_y = (end.y - start.y) / speed;

    //Move the sprite
    mover.sprite.move(delta_x, delta_y);

    //Check if the sprite has met the end
    if (mover.sprite.getPosition() == end)
        return true;

    return false;
}

(这里的 SF :: Vector2f 基本上与 X Y A结构浮点参数,如:在XY网格点)

(Where sf::Vector2f is basically a struct with an x and y float parameter, e.g. a point on an x-y grid)

不出所料,这个功能有一个可能性,通过终点后,由于浮动的舍入永不返回true。我用在这种情况下有什么算法有不管舍入我的精灵土地结束点正好在,?

Unsurprisingly, this function has a possibility to never return true after passing the end point due to the rounding of float. What algorithm do I use in this scenario to have my sprite land exactly on the end point, regardless of rounding?

注:隐忍不回答我的问题。这仅仅是一种妥协。我想要挑选完美点的第一次,无论任何四舍五入的算法。如果这是不可能的,让我知道。

Note: Tolerance is not an answer to my question. It is merely a compromise. I want the algorithm that picks the points perfectly the first time, regardless of any rounding. If this is impossible, let me know.

推荐答案

我想你,因为浮动你不应该做 mover.sprite.getPosition()==结束但是,看看 mover.sprite.getPosition() - 结束越小则一些数字,可以说

i think you have the answer already, because of the rounding of float you should not do mover.sprite.getPosition() == end but to see if mover.sprite.getPosition() - end is smaller then some number, lets say

 float diff = mover.sprite.getPosition() - end;

 if (diff < 0)
    diff *= -1;

 //Check if the sprite has met the end
 if (diff > 0.01)
        return true;

这样,你不检查,如果你在现场,但如果你足够近的地方。 改善你也可以做:

that way you check not if you are on the spot but if you are close enough to the spot. to improve that you can also do:

 float diff = mover.sprite.getPosition() - end;

 if (diff < 0)
    diff *= -1;

 //Check if the sprite has met the end
 if (diff > 0.01){
        mover.sprite.getPosition() = end; //this might not be the exact syntax but the idea is clear i hope
        return true;
 }