英文:
Random Walker (circle) move up much more frequent than other axis
问题
以下是翻译好的内容:
这是我做的一个小项目,只是为了好玩。我尝试使用libgdx在Java中重新创建随机漫步。
现在我认为我的代码相当成功,因为它(可能)正常工作。
但有一个问题,圆圈倾向于比其他轴更频繁地向上移动(沿y轴+方向)。
我已经花了两天时间来找出解决方案。仍然找不出我做错了什么。
以下是代码:
public class MyGdxGame implements ApplicationListener
{
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:
}
}
}
英文:
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:
}
}```
</details>
# 答案1
**得分**: 1
所以你在这里的问题是Random.nextInt(n)方法的上限是排除的。
// 返回0-9之间的数字
int next = ran.nextInt(10);
所以你需要使用
rand = r.nextInt(4);
你正在生成0->2之间的rand,你需要它是0->3,以包括沿着y轴向下移动。
<details>
<summary>英文:</summary>
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
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论