c++ - 随着时间 SFML C++ 移动时每隔几秒 Sprite

标签 c++ timer sfml

此代码相对于时间在屏幕上移动 Sprite 。然而,它似乎每隔几秒就会跳到左边。

int ogreMaxCell = 9;

if (SpriteVector[i].getPosition().x > ogreDirectionX[i]  )
{

    sf::Vector2f ogreDirection = sf::Vector2f(-1,0);
    float ogreSpeed = 1;
    sf::Vector2f ogreVelocity = ogreDirection * ogreSpeed * 250000.0f * dt.asSeconds(); 
    this->SpriteVector[i].move(ogreVelocity);
    //gets the spritesheet row
    orcSource.y = getCellYOrc(orcLeft);

}

if (ogreClock.getElapsedTime().asMilliseconds() > 250)
{
    orcxcell = (orcxcell + 1) % ogreMaxCell;

    ogreClock.restart();
}
SpriteVector[i].setTextureRect(sf::IntRect(orcSource.x + (orcxcell * 80), orcSource.y, 80, 80));

时间语句是:

    sf::Time                dt; // delta time
    sf::Time                elapsedTime;
    sf::Clock clock;
    elapsedTime += dt;
    dt = clock.restart();

关于为什么会发生这种情况的任何见解?

问候

最佳答案

你没有展示你是如何实现你的时间功能的,有两种可能性: 第一种可能性是你,你在 时间函数的循环,在那种情况下,结果是不同程度的运动,但从 if 结构来看,错误很可能在于可能性 2。250000.0f 是一个非常大的数字,在处理偏移量时必须使用,并且使用 ogre.clock 告诉我 #2 更有可能

2

时间函数的变量和声明都是循环的。 我将该函数放入编译器中,并将 cout 设置为以微秒的形式输出这两个值。 输出是 elapsedTime 始终为 0,并且 dt 始终在 0-4ish 微秒左右,除了偶尔出于某些原因它等于 400-2000ish 微秒。

这样做的结果是,它使您必须使用第二个时钟来控制时间,这样您的动画才不会出现故障,并且您的动画会时不时地跳到左边,因为 dt 从 4 微秒变为随机 1500 微秒。它还解释了为什么您必须乘以这么大的常数,因为您使用的是毫秒,并且不断得到 dt 的无穷小值。

time函数有几个问题 dt = clock.restart(); =/= 0 你总是会得到一些小的时间值,因为在将时钟重置为 0 并将时钟的值提供给 sf::time 变量所花费的时间。 当动画跳跃时,这是因为在那个特定的周期中,计算机在时钟重置后花费了更长的时间来分配值。

修复非常简单: 在循环结构外声明变量, 并像这样调整代码:

//declare before loop, if you dont, elapsed time constantly gets set to 0
sf::Time                dt; // delta time
sf::Time                elapsedTime;
sf::Clock clock;
//startloop structure of your choice
elapsedTime += clock.getElapsedTime();
dt = clock.getElapsedTime();
clock.restart();

并将第二个if语句修改为

if (elapsedTime.asMilliseconds() > 250)
{
    orcxcell = (orcxcell + 1) % ogreMaxCell;

    elapsedTime = milliseconds(0)
}

sf::Time只是一个变量,时钟必须进行计数。
希望这会有所帮助。

附注总是在你的循环结构之外写声明,它在大多数时候都可以正常工作,但有时它会导致你得到像这样的奇怪错误,或者随机崩溃。

关于c++ - 随着时间 SFML C++ 移动时每隔几秒 Sprite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212904/

相关文章:

c++ - 使用多个分隔符 C++ 读取格式化数据

c++ - 开放数据结构 : ArrayQueue

java - 调整窗口大小时使用面板中设置的图标调整 JLabel 的大小

javascript - NodeJS 设置超时

c++ - 如何从凸形中形成凹形?

c++ - 为什么 std::uncaught_exception 会变成 std​​::uncaught_exceptions?

c++ - 将 new 与使用 C malloc 的 C++ 构造函数一起使用

python - Timer 类驻留在 python 中的哪个模块中?

c++ - OpenCV 垫到 SFML 图像

c++ - unique_ptr - 无效指针和段错误