How to Spin a PShape Object

edited November 2017 in Questions about Code

I am trying to get a square, defined via a PShape object, to spin around its center. This is my code:

PShape square;

void setup()
{
  size(640,480, P3D);
  smooth();
  shapeMode(CENTER);

  square = createShape();

  square.beginShape(QUADS);

  square.stroke(0);

  square.vertex(0, 0, 0);
  square.vertex(0, 40, 0);
  square.vertex(40, 40, 0);
  square.vertex(40, 0, 0);

  square.endShape(CLOSE);
}

void draw()
{
  background(255);

  translate(width / 2, height / 2);

  square.rotate(radians(3));

  fill(0, 255, 255);
  rect(0, 0, 640, 480);
  shape(square, 0, 0);
}

When I run this code, the square's initial position is correct, but the rotation is not; it appears as though the upper left vertex oscillates while the shape rotates. Ultimately, I want to be able to spin the object around its center regardless of where it is positioned in the sketch. Any help towards accomplishing this would be appreciated.

Answers

  • PShape square;
    float a; 
    void setup()
    {
      size(640, 480, P3D);
    
      square = createShape();
    
      square.beginShape(QUADS);
      square.stroke(0);
      square.vertex(-20, -20, 0); // !!!!!!!!!!!!!!!!!!!!!!!
      square.vertex(-20, 20, 0);
      square.vertex(20, 20, 0);
      square.vertex(20, -20, 0);
      square.endShape(CLOSE);
    }
    
    void draw()
    {
      background(255);
    
      translate(width / 2, height / 2);
      rotate(radians(a));
    
      fill(0, 255, 255);
    
      shape(square, 0, 0, 
        40, 40);
    
      a+=0.7;
    }
    
  • Answer ✓

    This tutorial is a good introduction to transformations (rotation, translations,scaling) in Processing: https://processing.org/tutorials/transform2d/

    Kf

  • Thank you both! The code changes you made, Chrisir, and the information in the documentation you provided, kfrajer, have clarified my confusion with how rotation works in Processing.

Sign In or Register to comment.