0

我正在编写游戏;我有一个可以在该区域移动的 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 iget 相同的值。这意味着,所有人都朝着同一个方向 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;
4

3 回答 3

3

问题是您在每次通话中都在重新播种 RNG。

删除srand ( time(NULL) );所有方法中的行,它们将按预期工作。

为了使代码更好,我建议在您的主要srand(time(NULL );方法(而不是获取随机数的方法)的开头插入,一旦您完成了大部分错误的消除。

根据 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-30T14:09:56.270 回答
2

每次您打电话时,srand ( time(NULL) );您都在播种相同的值。

在您的应用程序开始时调用srand ( time(NULL) );一次,它应该可以解决您的问题。

于 2013-09-30T14:10:46.750 回答
1

您的变量 current_step、current_direction 和 current_wait 不应被声明为静态的。将它们声明为静态会告诉编译器这三个值应该在对 move around 方法的所有调用之间共享。结果是您第一次为它们生成随机值,但是对于每次连续调用都不会生成新的随机值,因为它们已经被分配了。

于 2013-09-30T17:25:08.063 回答