Hi, I'm working on a 2D project in OpenGL and now trying to optimize it, and basically I wondered
if you could take a look at the code and tell me if there are any faster ways of doing it.
I think it's the drawing that is time consuming and that's why I posted it here in the OpenGL
department.
The part that I am interested in handles the units, I have a chain where every unit knows
the adress to the previous and the next unit, and one controller that knows the adress
to the first and last unit. Every frame the controller tells the first unit to update itself, then
the first unit tells the next unit to update, etc etc.
For example I tried removing the glLoadIdentity() and positioning the unit relative to the
last unit, but that was no success.
Here is the code that every unit executes:
void unit::Update()
{
//calculate the direction to the target
if (TC.tank1->getX() > x)
dir = atanf((y - TC.tank1->getY()) / (TC.tank1->getX() - x));
else
dir = pi - atanf((y - TC.tank1->getY()) / (x - TC.tank1->getX()));
x += v*cosf(dir);
y -= v*sinf(dir);
//////////////////////////////////////
// Perform collision detection //
//////////////////////////////////////
float r=18.0f;
if ((TC.tank1->getX() - x) < r && (TC.tank1->getX() - x) > -r)
if (TC.tank1->getY() - y < r && TC.tank1->getY() - y > -r)
{
//the unit is inside the tank quad
dead = true;
}
//////////////////////////////////////
// Draw the unit //
//////////////////////////////////////
glLoadIdentity();
glTranslatef(x,y,-1.0f);
//translate radians to degrees
glRotatef(-dir*57.29577, 0, 0, 1);
glBegin(GL_QUADS);
// glNormal3f( 0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-16.0f, -16.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(16.0f, -16.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(16.0f, 16.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-16.0f, 16.0f, 0.0f);
glEnd();
// if there are more units, update them too
if (unit_next != 0)
unit_next->Update();
if (dead)
delete this;
}
Here is the class declaration (not really important?):
class unit
{
public:
float getX();
float getY();
unit *unit_next; //keeps the adress to the next unit, creates one big chain of units
unit *unit_previous; //keeps the adresss to the previous....
void Update();
private:
float x;
float y;
float dir; //the current direction to target
float v; //velocity
bool dead; //dead or not
};