Random Walker (circle) move up much more frequent than other axis

Nikolai Aleksandrovsk :

So this is a little project by me , just for fun. Ive tried recreating random Walker in Java by using libgdx.

Now I consider my code pretty much successful as it's working properly (perhaps).

But there is this one problem, the circle tends to move upward(yaxis+) much more frequent than other axis.

It's been 2 days for me to figure out the solution. Still can't find where did I do wrong.

So here's the code

{
    ShapeRenderer sr;
    OrthographicCamera cam;
    Random r;
    int rand;
    float x;
    float y;

    @Override
    public void create()
    {
        sr = new ShapeRenderer();
        cam = new OrthographicCamera();
        cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

        r = new Random();

        x = Gdx.graphics.getWidth()/2;
        y = Gdx.graphics.getHeight()/2;
    }

    @Override
    public void render()
    {        
        cam.update();   

        rand = r.nextInt(3);



        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sr.begin(ShapeRenderer.ShapeType.Filled);
        sr.setColor(Color.RED);
        sr.circle(x, y, 10);
        sr.end();

        switch(rand)
        {
            case 0:
                x = x + 100 * Gdx.graphics.getDeltaTime();
                break;

            case 1:
                x = x - 100 * Gdx.graphics.getDeltaTime();
                break;
            case 2:
                y = y + 100 * Gdx.graphics.getDeltaTime();
                break;

            case 3:
                y = y - 100 * Gdx.graphics.getDeltaTime();
                break;
                default:

        }
    }```
JoeChris :

So your problem here is the upper bounds on a Random.nextInt(n) method is exclusive

    // Returns number between 0-9 
    int next = ran.nextInt(10); 

So you need to use

    rand = r.nextInt(4);

What you're doing is generating rand between 0->2, you need it to be 0->3 to include the y axis to go down

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409968&siteId=1