How to get access to x & y of a PVector in an array List of PVectors?

Hi all, it seems a bit of a longwinded title but I have an array of PVectors which I want to get the x & y co ordinates from in order to draw a PShape. The issue I have is line 24, this points.get() approach worked when I was just grabbing the x and y separately from an array of floats but like this I can't get to the x & y variables within the PVector. points.get(i).x doesn't work either. I'm sure it's probably a simple solution and i'm brainfarting. Assistance would be appreciated, thanks.

Code below:

PShape shape;  
ArrayList points = new ArrayList<PVector>();
PVector temp = new PVector();

void setup() {
  size(800, 800); 
}

void draw() 
{
  //populating the array with PVectors
  for (int i = 0; i < 11; i++)
  {
    temp.x = (float)random(0, width-50);
    temp.y = (float)random(0, width-50);
    points.add(temp);
  }

  //creating the shape
  shape = createShape();
  shape.beginShape();
  shape.fill(0, 0, 255);
  shape.noStroke();
  shape.vertex(points.get(0), points.get(1));
  shape.bezierVertex(points.get(2), points.get(3), points.get(4), points.get(5), points.get(6), points.get(7));
  shape.bezierVertex(points.get(8), points.get(9), points.get(10), points.get(11), points.get(12), points.get(13));
  shape.bezierVertex(points.get(14), points.get(15), points.get(16), points.get(17), points.get(18), points.get(19));
  shape.vertex(points.get(20), points.get(21));
  shape.endShape();

  //drawing the shape
  shape(shape, 25, 25);
}
Tagged:

Answers

  • This code works for me.

    Kf

    ArrayList points = new ArrayList<PVector>(10);
    
    void setup() {
      size(800, 800); 
      noLoop();
    }
    
    void draw() 
    {
    
      for (int i = 0; i < 11; i++)
      {
        PVector temp = new PVector();
        temp.x = random(0, width-50);
        temp.y = random(0, width-50);
        points.add(temp);
      }
    
      for (int i = 0; i < 11; i++)
      {
        float x = ((PVector)points.get(i)).x;
        println(i+"\t"+x);
      }
    
    }
    
  • edited August 2016

    If you use

    ArrayList<PVector> points = new ArrayList(10);
    

    Then you don't need to cast the result of the get () in line 21.

  • Answer ✓

    @ line #2 ArrayList points = new ArrayList<PVector>();, the variable points is of datatype ArrayPoints. However the generic type wasn't specified. Although you've specified it when instantiating it w/ new, it's more important for the variable declaration to have the generic type: ArrayList<PVector> points = new ArrayList();.
    Or even better, both sides have it: ArrayList<PVector> points = new ArrayList<PVector>();

  • edited August 2016

    Thankyou to all of you for the assistance.

Sign In or Register to comment.