我正在编写游戏;我有一个可以在该区域移动的 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);
在这种情况下,有 2 个 NPC,但即使我尝试 50 个 NPC,都走向相同:方向、步骤、站立时间。
我怎样才能得到不同的值?
我试图在这个网站上阅读任何指南或任何关于随机的问题,但没有任何问题。我也尝试将 srand 放在不同的位置,但所有 NPC 仍然朝着相同的方向前进。也许有 SDL 函数来获取随机值?
关于 for 的另一件事:如果我一直删除for i
get 相同的值。这意味着,所有人都朝着同一个方向 1 方向
完整的移动代码:
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;