a question about VerletParticle2D - Toxiclibs

edited October 2013 in Library Questions

I am trying to learn the Toxiclibs library. It is a very simple example, attaching two particle with a spring (full code attached below).

I attempted to draw a rectangle on my Particle2 class function (see below) and the drawing procedures involve rotation (which messed up everything!). However, when I moved all the drawing procedure from the class outside to the draw loop, it works! It is the same code but somehow inside the class function, it doesn't work, but out in the draw loop, it works. why is it? I must have overlooked something about VerletParticle2D class?!

class Particle2 extends Particle{
  Particle2(Vec2D loc) {
    super(loc);
  }

  void display() {   
   //somehow drawing within the class function, rotate does not work properly
   rectMode(CENTER);
   pushMatrix();
   translate(x,y); 
   rotate(getVelocity().heading());
   rect(0,0,32,32);
   popMatrix();

  }
}


class Particle extends VerletParticle2D {

  Particle(Vec2D loc) {
    super(loc);
  }

  // All we're doing really is adding a display() function to a VerletParticle
  void display() {
    fill(127);
    stroke(0);
    strokeWeight(2);
    ellipse(x,y,32,32);

  }
}



import toxi.physics2d.*;
import toxi.physics2d.behaviors.*;
import toxi.geom.*;

// Reference to physics world
VerletPhysics2D physics;

Particle p1;
Particle2 p2;

void setup() {
  size(640,360);

  // Initialize the physics
  physics=new VerletPhysics2D();
  physics.addBehavior(new GravityBehavior(new Vec2D(0,0.5)));

  // Set the world's bounding box
  physics.setWorldBounds(new Rect(0,0,width,height));

  // Make two particles
  p1 = new Particle(new Vec2D(width/2,20));
  p2 = new Particle2(new Vec2D(width/2+160,20));
  // Lock one in place
  p1.lock();

  // Make a spring connecting both Particles
  VerletSpring2D spring=new VerletSpring2D(p1,p2,160,0.01);

  // Anything we make, we have to add into the physics world
  physics.addParticle(p1);
  physics.addParticle(p2);
  physics.addSpring(spring);
}

void draw() {
  // Update the physics world
  physics.update();

  background(255);

  // Draw a line between the particles
  stroke(0);
  strokeWeight(2);
  line(p1.x,p1.y,p2.x,p2.y);

  // Display the particles
  p1.display();
  //p2.display();

  //drawing in the draw loop works perfectly

  rectMode(CENTER);
  pushMatrix();
  translate(p2.x,p2.y); 
  rotate(p2.getVelocity().heading());
  rect(0,0,32,32);
  popMatrix();


  // Move the second one according to the mouse
  if (mousePressed) {
    p2.lock();
    p2.x = mouseX;
    p2.y = mouseY;
    p2.unlock();
  } 
}
Sign In or Register to comment.