Moving individual object rather than altogether in a for-loop (ArrayList)

hi, i am trying to get this moved individually instead of moving altogether at once. my objects are created in a loop, is there a way to get them to move individually instead? here’s my code, thanks in advanced!

public void drawBar()
		for(int i = 0; i < bar.size(); i++)
			float y = map(i, 0, bar.size(), 50, 600);

			rect(0, y - 20, 50 + value, 30);

public void mouseDragged()
		value = mouseX;

1 Like

hello and welcome to the forum!

Great to have you here!

Unfortunately you don’t show your entire code. So we can’t run this.

When you have a ArrayList bar of objects of class Bar, then you should use the x,y therein (when you haven’t defined them please do. For individual movement it is essential that each rectangle has stored its individual position and size.).

Like within the for-loop

     Bar currentBar = bar.get(i); 
     rect( currentBar.x, currentBar.y - 20, 
                  50 + currentBar.value, 30);

value would be the width of each rect (and 30 its height).

Drag and drop

When it comes to drag and drop: let’s say you pick a rect (with a for loop in mousePressed()): then store the number of the rect as dragID (global variable) and use this: bar.get(dragID).x += pmouseX-mouseX; or so.

I did this once with

  • one spot to drag on the center of the rect (for position) and
  • one spot at the lower right corner to start dragging (for size).

I used dist() to find out which spot was pressed with the mouse and on which rect.
See reference: Reference /

Create the objects

This is a good start!

It should happen in setup().

Like with a for loop and bar.add (…);

Here you could say (assuming your class is named Bar and the ArrayList is of type Bar) :
bar.add ( new Bar ( random (30,width-30), random(30,height-30) );

This assumes that your class Bar has a constructor that can receive x and y position.

Then each rectangle knows and stores its position. Then in draw use the position

rect( currentBar.x, currentBar.y - 20, 
                  50 + currentBar.value, 30);

There is a nice tutorial about objects: Objects /

Please show your entire code.

Warmest regards,

Chrisir :wink:

1 Like