这不应该给我当前的日期/时间(以秒为单位)吗?
我想根据当前时间(以秒为单位)计算振荡偏移值,以便任何对象都可以调用此方法,并获得返回的偏移量,该偏移量与调用同一方法的任何其他对象同步。
这是我的 locationOffset 属性的设置器:
- (float)locationOffset
{
float currentTime = [[NSDate date] timeIntervalSince1970];
locationOffset = sinf(currentTime);
CCLOG(@"--- current time = %1.9f, location offset = %1.1f", currentTime, locationOffset);
return locationOffset;
}
我将其称为 60Hz,输出如下所示:
--- current time = 1316013568.000000000, location offset = -0.1
...并且它保持这种方式。小数点后的所有内容都应该为零吗?
我希望我可以通过缩放 currentTime 来调整频率,并通过缩放 offsett 来调整“波长”,但我只需要让我的正弦 locationOffset 根据时间来回摆动。
看起来位置偏移量应该每 2pi 秒从 -1 到 1 循环。
编辑:添加现在可以正常工作的方法。
- (float)locationOffset
{
double currentTime = [[NSDate date] timeIntervalSinceReferenceDate];
locationOffset = sin(2.0f*currentTime) * 12.0f;
// CCLOG(@"--- current time = %1.9f, location offset = %1.1f", currentTime, locationOffset);
return locationOffset;
}
它每 pi 秒循环一次,大小为 +/- 12。
I want to calculate an oscillating offset value based on the current time in seconds so that any object can call this method and would get an offset returned that is synchronized to any other object that calls the same method.
This is my setter for the locationOffset property:
- (float)locationOffset
{
float currentTime = [[NSDate date] timeIntervalSince1970];
locationOffset = sinf(currentTime);
CCLOG(@"--- current time = %1.9f, location offset = %1.1f", currentTime, locationOffset);
return locationOffset;
}
I'm calling this a 60Hz and the output looks like this:
--- current time = 1316013568.000000000, location offset = -0.1
...and it stays this way. Should everything after the decimal be zero?
I expect that I can adjust the frequency by scaling currentTime and the "wavelength" by scaling the offsett, but I just need to get my sinusoidal locationOffset to swing back and forth based on the time.
It seems like the location offset should cycle from -1 to 1 every 2pi seconds.
EDIT: Adding the method that works now as it should.
- (float)locationOffset
{
double currentTime = [[NSDate date] timeIntervalSinceReferenceDate];
locationOffset = sin(2.0f*currentTime) * 12.0f;
// CCLOG(@"--- current time = %1.9f, location offset = %1.1f", currentTime, locationOffset);
return locationOffset;
}
It cycles every pi seconds and has a magnitude of +/- 12.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您的问题是
float
值只有大约 7 位有效数字。您甚至没有足够的精度来正确表达整数值 1316013568,因此您实际上一次又一次地将相同的值输入到sinf
中。坚持使用 double 值,并使用双精度 sin 函数,或者在转换为浮点数之前将数字缩放到小于约 6 个整数位的值。Yep, your problem is that a
float
value only has about 7 significant digits. You don't even have enough precision to express the integer value 1316013568 correctly, so you're effectively feeding the same value intosinf
again and again. Stick withdouble
values, and use a double-precisionsin
function, or scale the number to a value less than about 6 integer digits before converting to float.