Search code examples
libgdx

How to make an equivalent SpriteBatch.draw() to Sprite.draw()?


I draw the same sprite by calling draw on the sprite and by calling draw on the SpriteBatch right after.

target.sprite.draw(game.batch);

game.batch.draw(target.sprite, target.sprite.getX(), target.sprite.getY(), 
                target.sprite.getOriginX(), target.sprite.getOriginY(),
                target.sprite.getWidth(), target.sprite.getHeight(),
                target.sprite.getScaleX(), target.sprite.getScaleY(),
                target.sprite.getRotation(), false);

... but the second call draws the sprite at a 90 degree angle compared to the first one. When I subtract 90 degrees to compensate, the sprites don't align because they are rotating around the same point relative to the screen but different points relative to themselves (the one drawn with the SpriteBatch.draw() call is rotating around the origin of the one drawn with the Sprite.draw()).

How do I make an equivalent Sprite.Batch.draw() call?


Solution

  • It's a little tricky to tell from the code you posted, but I think you're calling the following function:

    /** Draws a rectangle with the texture coordinates rotated 90 degrees. The bottom left corner at x,y and stretching the region
     * to cover the given width and height. The rectangle is offset by originX, originY relative to the origin. Scale specifies the
     * scaling factor by which the rectangle should be scaled around originX, originY. Rotation specifies the angle of counter
     * clockwise rotation of the rectangle around originX, originY.
     * @param clockwise If true, the texture coordinates are rotated 90 degrees clockwise. If false, they are rotated 90 degrees
     *           counter clockwise. */
    public void draw (TextureRegion region, float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float rotation, boolean clockwise);
    

    The key thing to note here is that the fourth and fifth parameters are not the origin you want to rotate around, but rather an offset from that origin. If you want the functionality to match sprite.draw(), you should pass 0 as the originX and originY.

    If you want to avoid the 90* rotation (which appears to be very intentional; I'm thinking it might be so that you can define 0 degrees or radians as being "up" instead of "right", if that makes sense), you should use the overloaded version of that function which omits the last parameter (boolean clockwise).

    You can find all of this in the libGDX source code for the Batch interface (which SpriteBatch is implementing).