Search code examples
javascriptanimationrotationprocessingrect

rotate command translates rect to another position processing


I have rotated rect by 35 in processing.Here is my code.

pushMatrix();
rotate(35);
stroke(74, 73, 74);
fill(156, 153, 153);
rect(cannon1PositionX,cannon1PositionY,25,60,50);
noStroke();
fill(173, 168, 173);
rect(cannon1PositionX + 3,cannon1PositionY + 4,20,50,50);
popMatrix();

But if i change rotation to 40 the rect is rotated and translated to another position. How to fix this?


Solution

  • Your issue is that when you first use rotate() you are rotating in reference to the whole canvas so then when you use canon1PositionX, cannon1PositionY depending on the angle you are currently facing the canvas the position changes.

    What you would need to do is the following:

    pushMatrix();
    // Go to the cannon position
    translate(cannon1PositionX, cannon1PositionY);
    // Rotate to the right angle
    rotate(35);
    // Draw the cannon at the current position and with the right angle
    rect(0, 0, 25, 60, 50);
    // Draw the second cannon next to the current one
    rect(3, 4, 20, 50, 50);
    popMatrix();