[SOLVED] Physics engine to balance objects on moving objects

Hi everyone,

I am looking for a way to move an object like a rectangle by keyboard that has another object placed on top of it. I want to control the movements of the bottom object while the upper object should balance on it and therefore follow its movements. It should fall down when the bottom object is tilting.

Using ofxBox2d the upper object does not move until the bottom one is almost gone, then it falls off. I move the object by setting its position. When I move the object by using force, it is collapsing. I also thought that the friction might be relevant but this doesn’t seem to be the case. I tried to illustrate my problem in the following image:

What am I missing? Is there a proper way to do this? Or another library?

Thanks,
Deborah

1 Like

Try this:

ofxBox2d box2d;
ofxBox2dRect black_rect, green_rect;

//--------------------------------------------------------------
void ofApp::setup(){
	box2d.init();
	box2d.setGravity(0, 10);
	box2d.createBounds();
	box2d.setFPS(30.0);
	
	float d = 100;
	black_rect.setPhysics(1.0, 0.0, 0.01);
	black_rect.setup(box2d.getWorld(), 100, ofGetHeight()-d/3, d/3, d);
	green_rect.setPhysics(1.0, 0.0, 10.0);
	green_rect.setup(box2d.getWorld(), 100, ofGetHeight()-d, d, d/3);
}

//--------------------------------------------------------------
void ofApp::update(){
	box2d.update();
	black_rect.addForce(ofVec2f(10, 0), 1);
	//float d = 100;
	//black_rect.setPosition(ofVec2f(100 + ofGetFrameNum(), ofGetHeight()-d/3));
}

//--------------------------------------------------------------
void ofApp::draw(){
	ofFill();
	ofSetColor(ofColor::black);
	black_rect.draw();
	ofSetColor(ofColor::green);
	green_rect.draw();
	
	box2d.drawGround();
}

You need to set the green rect’s friction large enough so that it doesn’t slip off from the black rect. Also you should use addForce(...) since setPosition(...) won’t be affected by friction.

2 Likes

Awesome, great example. My mistake was to lower the world gravity before raising the friction. With a gravity of 1 it’s not working. Thank you!