我想以随机的方式移动asteriods。我通过在asteriods作为paramenter的载体,以防止在屏幕就这样画上了asteriods的多重绘图方法开始清除屏幕:
然而,与我的编码代码,所有的小行星在同一方向上移动。我需要使它随机运动,请大家帮忙。下面是我的代码:
void Entity::move(GLFWwindow * window, vector<Entity> allAsteriods, Entity &sp ) {
DrawEntity de = DrawEntity();
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < allAsteriods.size(); i++) {
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
float x = allAsteriods[i].return_PositionVector().back().get_X();
float y = allAsteriods[i].return_PositionVector().back().get_Y();
glPushMatrix();
glTranslatef(x, y, 0.0); // 3. Translate to the object's position.
de.drawEntity(allAsteriods[i]);
float additionalX = GenerateRandom(0.10, 0.90);
float additionalY = GenerateRandom(0.10, 0.90);
allAsteriods[i].addTo_PositionVector(x + additionalX, y + additionalY);
glPopMatrix();
}
de.drawEntity(sp);
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
}
您要添加一个随机位置,以您的小行星每帧(你可以看到他们是如何围绕轻摇他们向下移动屏幕)。你的随机位置只能从0.1到在X和Y两个0.9,所以他们只会向屏幕的左下方移动。
为了解决这个问题,你需要做到以下几点:
Velocity
载体。allAsteroids[i].velocity.x = GenerateRandom(-1.0, 1.0)
allAsteroids[i].velocity.y = GenerateRandom(-1.0, 1.0)
//Not sure why you're doing it like this - it should be easy to get X and Y from vectors, but I'll do it the same way:
float velX = allAsteriods[i].return_VelocityVector().back().get_X();
float velY = allAsteriods[i].return_VelocityVector().back().get_Y();
allAsteriods[i].addTo_PositionVector(x + velX, y + velY);
另外,您
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
不应该通过里面所有的小行星的循环。这应该是在你的游戏循环的顶部每帧只需要做一次。您的每小行星循环应该有glPushMatrix()
开头和结尾glPopMatrix()