所以我在Java游戏中实现跳转时会使用这段旧代码。
它看起来像这样:
//Vars
final int Y_ZERO_POINT = 580;
double height = 0, speed = 4;
public static final double gravity = 9.81;
double x = 25;
int y = (int) (Y_ZERO_POINT-(height*100));
long previous, start = 0;
// Code in my game loop
start = System.nanoTime();
if(previous != 0 && up){
double delta = start - previous;
height = (height + (delta/1000000000) * speed);
speed -= (delta/1000000000) * gravity;
y = (int) (Y_ZERO_POINT-(height * 100));
}
previous = start;
现在我想在C ++游戏中实现类似的功能。
在这里阅读:http://www.javacodegeeks.com/2012/02/what-is-behind-systemnanotime.html
我了解到Java System.getNanoTime()
在Linux系统中使用clock_gettime(CLOCK_MONOTONIC, &ts);
。
所以我在我的C ++代码中使用它并实现相同的跳转代码: https://github.com/Veske/CPP-Learning/blob/master/kodutoo3/player/player.cpp
差别很大。在Java中,跳转始终是一致的,并且应该以它应该结束。在我的C ++程序中,跳转有时就像在Java中一样,但大多数情况下它会发生根本性的变化。我从clock_gettime()
获得的时间有时会跳跃很多,这会导致游戏中的自我跳跃也看起来非常随机。角色有时会跳出屏幕然后再次正常跳跃。
是否可以像在Java中那样从C ++时间函数获得一致的结果,或者我应该考虑为我的跳转机制使用不同的方法?
答案 0 :(得分:2)
如果您有C ++ 11编译器,则可以使用可移植的<chrono>
标头。
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
auto t0 = chrono::steady_clock::now();
auto t1 = chrono::steady_clock::now();
auto dt = t1 - t0;
cout << "t0: " << chrono::time_point_cast<chrono::nanoseconds>(t0).time_since_epoch().count() << " ns" << endl;
cout << "t1: " << chrono::time_point_cast<chrono::nanoseconds>(t1).time_since_epoch().count() << " ns" << endl;
cout << "dt: " << chrono::duration_cast<chrono::nanoseconds>(dt).count() << " ns" << endl;
return 0;
}
示例输出:
t0: 2800906746162 ns
t1: 2800906746345 ns
dt: 183 ns
对于时差测量,请务必使用不可调整的(a.k.a。单调)时钟,如steady_clock
。更多信息here。