How to "attach" a box to another box

The best example I can think of for what I mean is coding something similar to a ferris wheel. Say we have:

function draw() {

	background(20);

	push();

		rotateZ(frameCount * 0.01);
		fill(255, 0, 0);
		box(300, 5, 5);

	pop();

	push();

		rotateZ(frameCount * -0.01);
		fill(0, 0, 255);
		sphere(20, 20);

	pop();
}

Is there a way to “pin” the sphere to one end of the long “stick” box, so that its rotations etc all happen relative to the end of the box? Basically can you create groups of shapes where if I transform the parent, all children will stay in their same position relative to the parent shape, and can also have their own transformations.

Is this achievable?

EDIT: It seems this is done by nesting with push() and pop(), here’s the working code:

function draw() {

	background(20);
	fill(200);

	push();

		translate(0, 50, 0);
		rotateY(-frameCount * .01);

		push();
		
			translate(75, 0, 0);
			box(150, 5, 5);

			push();

				translate(75, 0, 0);
				rotateX(frameCount * .01);
				rotateY(frameCount * .01);
				rotateZ(frameCount * .01);
				box(30, 30);

			pop();

		pop();

	pop();
}
3 Likes

Yes, you accomplish this with the createShape(GROUP) method as referenced here:
https://processing.org/reference/createShape_.html the group example is the last example in the list if you want to apply transformations to the child objects you will have to recreate the shape.

Forgive me if I’m being slow here but the syntax and functions on that Processing page looks different to what I’ve been learning on p5js.org Reference page, am I missing something obvious here?

It really depends on what you are trying to attach a box to another box for.

For a simple case, I recommend looking at the p5.js examples list: Arm

https://p5js.org/examples/transform-arm.html

See also, Chain:

https://p5js.org/examples/simulate-chain.html

If you want to do something more complex with lots of boxes all connected by articulation points, then I suggest Box2D for p5.js. Shiffman has a lot of intro Box2D tutorials on YouTube, and it is perfect for connecting boxes to other boxes via connection points (or springs, etc).

https://www.google.com/search?q=p5.js+box2d

2 Likes