我无法为我的 GLUT 小行星游戏显示和动画多个小行星。我可以生成 1 ok,但是当我尝试添加更多输出时,输出不正确,createasteroid 不断被调用,并且出于某种原因在屏幕的不同部分闪烁小行星几毫秒。我相信这可能是因为显示功能结束时对象被破坏但我无法找到解决方法这是我到目前为止的代码:
小行星.h
class asteroid
{
public:
asteroid(void); //constructer
~asteroid(void); //deconstructer
void createAsteroid();
float generateAsteroidLocation(float a, float b);
void animateAsteroid();
};
小行星.cpp
#include "asteroid.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <ctime>
#include <GL/glut.h>
float asteroidX,asteroidY, V;
int numOfAsteroids=0;
asteroid::asteroid(void){
}
asteroid::~asteroid(void){
}
void asteroid::createAsteroid(){
// Translate to an area outside of the screen and then give a random velocity in the direction of the player
asteroidX = generateAsteroidLocation(0, 30);
asteroidY = generateAsteroidLocation(0, 30);
V = generateAsteroidLocation(0.000030, 0.000050);
printf("Asteroid Y Location %f \n", asteroidY);
printf("Asteroid X Location %f \n", asteroidX);
printf("Asteroid Velocity %f \n", V);
printf("Asteroid Created! \n");
glPushMatrix();
glTranslatef(asteroidX, asteroidY, 0.0);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_STRIP);
glVertex2f(1.0, 1.0);
glVertex2f(1.8, 0.0);
glVertex2f(1.4, -0.8);
glVertex2f(1.0, -1.7);
glVertex2f(-1.5, -1.0);
glVertex2f(-1.0, 0.0);
glVertex2f(0.0, 1.4);
glVertex2f(1.0, 1.0);
glEnd();
glPopMatrix();
}
float asteroid::generateAsteroidLocation(float a, float b){
float random = ((float) rand()) / (float) RAND_MAX;
float range = b - a;
return (random*range) + a;
}
void asteroid::animateAsteroid(){
float dt = 3500;
float Dx = 25 - asteroidX;
float Dy = 25 - asteroidY;
float Cx = asteroidX + Dx / sqrt(Dx*Dx+Dy*Dy) * V * dt;
float Cy = asteroidY + Dy / sqrt(Dx*Dx+Dy*Dy) * V * dt;
asteroidX = Cx;
asteroidY = Cy;
}
main.cpp(导致问题的函数)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <ctime>
#include "asteroid.h"
#include <GL/glut.h>
asteroid a1;
asteroid a2;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
// check to see if the player is ready, if not, show the splashscreen
if(ready == false){
splashScreen();
showText();
}
else{
createSpaceship();
// PROBLEM HERE
a1.createAsteroid();
a2.createAsteroid();
}
// Setup the scene
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 50, 0, 50, 0, 50);
// call the needed functions
glutSwapBuffers();
}
void idle(void)
{
glutPostWindowRedisplay(glutGetWindow());
// PROBLEM HERE
a1.animateAsteroid();
a2.animateAsteroid();
}
对此的任何帮助都会很棒。我对采取什么方法感到困惑。如果需要,我可以提供更多信息或粘贴箱。谢谢!-担