How to have one class with two positions?

edited October 2017 in How To...

Hello~ Sorry if my English is not very good i am still learning! my problem is that i have two rectangles which are both defined by the same class but i don't know how to have rectangle 1 in a different position than rectangle 2. if you need anymore info just ask :)

very much thank you! ~ Yoosuf

Answers

  • class TwoRects {
      PVector p0;
      PVector p1;
      color c;
      TwoRects(){
      p0 = new PVector( random(width-20), random(height-20) );
      p1 = new PVector( random(width-20), random(height-20) );
      c = color( random(255), random(255), random(255) );
      }
      void draw(){
        stroke(c);
        line(p0.x+10,p0.y+10,p1.x+10,p1.y+10);
        stroke(0);
        fill(c);
        rect(p0.x,p0.y,20,20);
        rect(p1.x,p1.y,20,20);
      }
    }
    
    TwoRects[] cherries = new TwoRects[5];
    
    void setup(){
      size(400,400);
      for( int i = 0; i < cherries.length; i++){
        cherries[i] = new TwoRects();
      }
    }
    
    void draw(){
      background(0);
      for( TwoRects c : cherries ) c.draw();
    }
    
  • edited October 2017

    Hello~ Thank you this is helping me much more -however- I need to be able to put the two boxes in set different positions opposed to random, how can I change code to make one box in a particular position and other box in different particular position?

    Very very much thanks for your amazing code though!!!! :)

  • edited October 2017 Answer ✓

    p0 and p1 are the PVectors that are the positions.

    You can either set these positions directly, or you can pass the positions you want in as parameters to the class's constructor function, or you can have class functions that can change the position:

    class TwoRects {
      PVector p0;
      PVector p1;
      color c;
      TwoRects(float x0, float y0, float x1, float y1){
      p0 = new PVector( x0, y0 );
      p1 = new PVector( x1, y1 );
      c = color( random(255), random(255), random(255) );
      }
      void draw(){
        stroke(c);
        line(p0.x+10,p0.y+10,p1.x+10,p1.y+10);
        stroke(0);
        fill(c);
        rect(p0.x,p0.y,20,20);
        rect(p1.x,p1.y,20,20);
      }
      void newPosition( float x ){
        p0.x = x;
      }
    }
    
    TwoRects t = new TwoRects(20, 20, 360, 360);
    
    void setup(){
      size(400,400);
    }
    
    void draw(){
      background(0);
      t.draw();
    }
    
    void mousePressed(){
      t.newPosition(mouseX);
      t.p0.y = mouseY;
    }
    
  • Thank you thank you so veryy much many hugs!~~

Sign In or Register to comment.