算法沿直线运动 [英] Algorithm for movement along linear line

查看:107
本文介绍了算法沿直线运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数如下:

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.

推荐答案

我想你,因为浮动你不应该做<四舍五入的答案已经,code> 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;
 }

这篇关于算法沿直线运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆