jeudi 12 août 2021

Why does rand() result not same?

I making a game in C and now, I making world generation for my game and I want to generate random numbers, but with same results.

Here is my code:

#include <stdlib.h>
#include <math.h>

#include "../../constants.h"
#include "../../game_constants.h"
#include "../../block/block.h"
#include "../world.h"
#include "../chunk.h"

int seed = 1;

int gen(BlockType type, int x)
{
    int ret = 0;
    switch (type)
    {
        case GRASS_BLOCK:
            return ret + 0.5;
            break;
        case DIRT_BLOCK:
            return ret + 0.5;
            break;
        case STONE_BLOCK:
            // The problem
            ret += 3 * sin(x + rand() + cos(seed));
            return ret + 0.5;
            break;
    }
}

void world_gen(World *world)
{
    int i;
    for (i = 0; i < loadedChunks * (SCREEN_X / BLOCK_SIZE); i++)
    {
        world_create_block(world, GRASS_BLOCK, i, gen(GRASS_BLOCK, i) + 16);
        world_create_block(world, DIRT_BLOCK, i, gen(DIRT_BLOCK, i) + 15);
        world_create_block(world, STONE_BLOCK, i, gen(STONE_BLOCK, i) + 11);
    }
}

(I will share full code if it needed)

Edit

srand() changes world generation.

When I use srand() (I don't like that world generation):

1

When I not use srand() (I like that world generation, but the problem is block positions are not same):

2




Aucun commentaire:

Enregistrer un commentaire