translating canvas for rotating sprites that shoot

| | August 18, 2015

I am trying to align bullets to my different sprites guns (top down 2D for android). Right now Im using this method to draw my bullets:

public void draw(Canvas canvas){    
    update();
    canvas.save();
    canvas.rotate(angle, x + width / 2, y + height / 2);
    canvas.translate(translaterX, translaterY);
    canvas.drawBitmap(bitmap, x, y, null);
    canvas.restore();
}

The problem here is the translater, Im always having to add or substract from it to make the bullets spawn from my gun when my sprites rotate and I cant figure it out, is there any standard value for this, like translaterX = bitmap.getwidth()/2? I dont really understand how the translater works and I feel like Ive tried everything, what am I missing? For the examples sake lets say that my gun is always in the middle of the bitmap.

Or is there even another way to do this that is simpler?

2 Responses to “translating canvas for rotating sprites that shoot”

  1. you’ll need to calculate the rotation of the gun from the center of the player sprite

    x = (float)Math.cos(playerAngle) * radius;
    y = (float)Math.sin(playerAngle) * radius;
    

    radius should be the distance that is from the player center to the position of the gun

  2. You have different point locations for each gun, relative to the location of your sprite. Correct?

    When you rotate your sprite, you need to rotate these points around the same center of rotation that you used for your sprite.

Leave a Reply