我正在编写一个游戏;我有一个NPC可以在这个区域内移动,但是有一个问题:由于随机值,它们都朝着相同的方向前进
这些是随机函数:
int MoveObjects::GetRandomDirectionToMove()
{
srand ( time(NULL) );
int x;
for(int i=0;i<5;i++)
x = rand() % 4 + 1;
return x;
}
int MoveObjects::GetRandomStepsToMove()
{
srand ( time(NULL) );
int x;
for(int i=0;i<5;i++)
x = rand() % 80 + 50;
return x;
}
int MoveObjects::GetRandomTimeToStand()
{
srand ( time(NULL) );
int x;
for(int i=0;i<5;i++)
x = rand() % 20 + 10;
return x;
}这是主要的
for(int i=0;i<2;i++)
npc[i].MoveAround(area);在这种情况下,有两个全国人民代表大会,但即使我尝试50全国人民代表大会,所有的走向相同:方向,步骤,时间站。
我怎么能得到不同的价值观?
我试着在这个网站上阅读任何关于随机的指南或问题,但是没有什么不起作用的。我也试着把srand放在不同的位置,但是所有的全国人民代表大会都朝着相同的方向发展。也许有SDL函数来得到随机值?
还有一件关于for的事情:如果我删除了for i,那么始终得到相同的值。这意味着,所有的方向都是一样的
全移动代码:
int frame = GetFrameCount();
frame++;
SetFrameCount(frame);
static int current_step = 0;
static int current_direction = 0;
static int current_wait = 0;
if(!current_step) {
current_step = GetRandomStepsToMove();
current_direction = GetRandomDirectionToMove();
current_wait = GetRandomTimeToStand();
}
if(!current_wait) {
if(current_direction == 1)
MoveUp(area);
else if(current_direction == 2)
MoveDown(area);
else if(current_direction == 3)
MoveRight(area);
else if(current_direction == 4)
MoveLeft(area);
current_step--;
if(current_step < 0) current_step = 0;
}
current_wait--;
if(current_wait < 0) current_wait = 0;发布于 2013-09-30 17:25:08
您的变量current_step、current_direction和current_wait不应声明为静态。声明它们是静态的,它告诉编译器这三个值应该在对move方法的所有调用之间共享。结果是第一次为它们生成随机值,但是每次连续调用都不会产生新的随机值,因为它们已经被分配了。
发布于 2013-09-30 14:09:56
问题是,您正在每个调用中重新播种RNG。
srand ( time(NULL) ); 从所有方法中移除的行,它们将按预期工作。
为了使代码更好,我建议在您的主要方法开始时插入srand(time(NULL ); (而不是获取随机的方法),一旦您完成了大多数bug的灭绝。
根据c++标准,实际上不需要调用srand来生成值;对rand的调用将表现为在程序开始时调用了srand(1)。
此外,您的随机代码实际上比需要的要复杂得多,我将解释为什么:
在这个方法中
int MoveObjects::GetRandomDirectionToMove() {
int x;
for(int i=0;i<5;i++)
x = rand() % 4 + 1;
return x;
}由于某种原因,你正在绘制五个随机数,但你只使用最后一个。这是一种浪费,您只需使用所绘制的第一个数字就可以做得很好。将其作为
int MoveObjects::GetRandomDirectionToMove() {
return rand() % 4 + 1;
}返回的结果也是随机的,同样不可预测,而且速度是原来的五倍。
发布于 2013-09-30 14:10:46
每次调用srand ( time(NULL) );时,都会播种相同的值。
在您的应用程序开始时调用srand ( time(NULL) );一次,它将解决您的问题。
https://stackoverflow.com/questions/19096321
复制相似问题