new object affecting the position of the previous ones
in
Programming Questions
•
6 months ago
Hi,
I am creating a new box from the top of the screen with keyPress and the new box pushes down the previous boxes. It is a simple scrolling boxes. But I can't find a way for the new objects affect the previous objects' location.
I made it work with 2 boxes, but this is where I'm stuck. I'd appreciate any insights on this.
- import java.util.Iterator;
- ArrayList<Box> boxes = new ArrayList<Box>();
- float newBoxHeight = 0.0;
- int boxID = 0;
- void setup() {
- size(600, 600, P2D);
- //create the first box on screen.
- newBoxHeight = random(100, 200);
- boxes.add( new Box(boxID, newBoxHeight) );
- boxID++;
- }
- void draw() {
- background(0);
- Iterator<Box> it = boxes.iterator();
- while ( it.hasNext () ) {
- Box b = it.next();
- b.update();
- b.display();
- if ( b.isOffscreen() ) {
- it.remove();
- }
- }
- println( boxes.size() );
- }
- void keyPressed() {
- newBoxHeight = random(100, 200);
- boxes.add( new Box(boxID, newBoxHeight) );
- //need to know the new box loc and the one before.
- Box b = boxes.get(boxID-1);
- b.setTargetLocation( boxes.get(boxID).boxHeight );
- boxID++;
- println("key Pressed");
- }
- class Box {
- float boxHeight;
- PVector loc = new PVector(); //current location
- PVector tloc = new PVector(); //target location
- color boxColor;
- int id;
- Box(int _id, float _bh) {
- id = _id;
- boxHeight = _bh;
- loc.y = -boxHeight;
- //tloc.set(0, 0, 0);
- boxColor = color( random(150, 250), random(140, 200), random(140, 200) );
- }
- /*
- int getID() {
- int _id = this.id;
- return _id;
- }*/
- //how can i get tloc.y of the next box?
- void setTargetLocation(float _nextTLoc) {
- tloc.y += _nextTLoc;
- }
- boolean isOffscreen() {
- return loc.y >= height;
- }
- void update() {
- loc.lerp(tloc, .1);
- }
- void display() {
- pushMatrix();
- translate(loc.x, loc.y);
- noStroke();
- fill(boxColor);
- rectMode(CORNER);
- rect(0, 0, width, boxHeight);
- popMatrix();
- }
- }
1