问题
I recently found a nice tutorial for enabling physics with Box2d for iOS.
http://www.cocoanetics.com/2010/05/physics-101-uikit-app-with-box2d-for-gravity/
I'm just wondering how to implement drag and drop for a UIView. Can anyone provide any direction? Thanks for your time.
回答1:
Well, always keep in mind, that everything in Box2D has to be moved by force (well, it's possible to set position directly, but if you want smooth physics movement, this won't do the trick).
So if you want to move some body accordingly to another body (body moved by touch) the joints are the best way to achieve this and guess what, there is joint type called MouseJoint, which is perfect for this situation (also could be used by multitouch).
b2MouseJointDef def;
def.bodyA=/*background_body*/;
def.bodyB=/*body of dragged view*/;
def.frequencyHz=60.0f;
def.dampingRatio=0.0f;
def.maxForce=x * def.bodyB->GetMass(); //i use this for same applied force depending on mass
def.collideConnected=YES;
def.target.Set(loc.x/PTM_RATIO, (self.bounds.size.height - loc.y)/PTM_RATIO);
bwMouseJoint joint=b2World->CreateJoint(def);
and then set position (target) of mouse joint
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint loc=[[touches anyObject] locationInView:view];
joint->SetTarget(b2Vec2(loc.x/PTM_RATIO,(view.bounds.size.height-loc.y)/PTM_RATIO));
}
...note, that this snipper contains undefined "variables" like PTM_RATION (if you don't understand them, check the basic tutorials or docs) and view(which is view containing dragged view), so take it as an idea, not copy&paste example:).
You create one joint (for each touch in multitouch app - but you need to track which touch represent thich mousejoint), and move joint's target to it's location. Because it's joint, the forces are applied to the bodyB appropriately (in fact, mouse joint applies large force, so it's almost like instant dragging).
For more info about joints, take a look at f.e. this tutorial: Box2D 2.1a Tutorial – Part 2 (Joints)
I hope my example is understandable, if any additional questions, don't hesitate to ask:).
来源:https://stackoverflow.com/questions/8886827/drag-and-drop-uiviews-with-box2d-ios