gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:55:06 25 4
gpt4 key购买 nike

此代码相对于时间在屏幕上移动 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com