I'm making a 2d top down game in Java using LWJGL(OpenGL, essentially). I recently tried adding a swinging sword mechanism. My coordinate system is set to the bottom left FOR ALL objects. The rotation worked, but it happens with respect to the bottom left corner of the Sword Quad. I want it to rotate with the center of the bottom line as the pivot for rotation. I tried a lot of solutions from the internet like:
- translating the object to origin(0,0 of the screen), then rotating, then translate to the point of pivot.
- translating object normally, then rotating, then again translating to the point you want it to pivot at.
But they all yield weird results.
Here's the code:
The Sword Class:
public class Sword extends GameObject {
private static int speed = 5, deg = 0;;
private Texture tex;
public Sword(float x, float y, ObjectId id) {
super(x, y, id);
//tex = ImageLoader.loadTexture(null, null);
}
protected void update(ArrayList<GameObject> objects) {
if(deg < 360) deg += 1;
else deg = 0;
}
protected void render() {
Draw.rect(x, y, 10, 32, deg, 1, 0, 0);
}
public Rectangle getBounds() {
return null;
}
}
The Draw.rect method:
public static void rect( float x, float y, float width, float height,
float deg, float r, float g, float b) {
glDisable(GL_TEXTURE_2D);
glPushMatrix();
{
glTranslatef(0, 0, 0);
glRotatef(deg, 0, 0, 1);
glTranslatef(x + (width/2), y, 0);
glColor3f(r, g, b);
glBegin(GL_QUADS); // Specifies to the program where the drawing
// code begins. just to keep stuff neat.
// GL_QUADS specifies the type of shape
// you're going to be drawing.
{
glVertex2f(0, 0); // Specify the vertices. 0, 0 is on BOTTOM
// LEFT CORNER OF SCREEN.
glVertex2f(0, height); // 2f specifies the number of args
// we're taking(2) and the type
// (float)
glVertex2f(width, height);
glVertex2f(width, 0);
}
glEnd();
}
glPopMatrix();
glEnable(GL_TEXTURE_2D);
}
EDIT: Here is an image of what "weird result" is. In the pic, I'm translating first to origin[(0, 0) of the WORLD], then rotating(by 90 degrees), then translating to translating to [x - (width/2) , y]. As you can see, the red block that represents the sword is out of the "arena", even though I've set the x, and y of the sword to near the player. The image: