Move body to a specific position - Box2D

℡╲_俬逩灬. 提交于 2019-11-28 17:33:52
Tom Guinther

The simplest way is actually to use SetPosition/SetTransform(position,angle). For example:

body->SetTransform(b2Vec2(0,0),body->GetAngle())

Obviously, the instantaneous jump means you are subverting the physics simulation but it is the simplest most direct way to set the position of a body.

Given that you don't want to use SetPosition (which is equivalent to the code posted above) then ApplyLinearImpulse with the appropriate force (based on the Mass and current speed of the body) will do the trick, and is more correct from a simulation point-of-view, but likely to be more problematic given potential side-effects, etc.

Anyway, iforce2d covered SetLinearVelocity..., and I would add that a mouse joint is very useful even when the "mouse" is not involved.

The simplest way would be to set the linear velocity of the body so that it will cover the necessary distance in one time step. eg. if the body needs to move (2,3) units to get to the desired location and your timestep is 60Hz you could SetLinearVelocity(120,180) for one time step. In the next time step you would of course have to set the velocity back to zero to stop it flying of into the distance. The result of this is not much different to if you had used SetTransform, except CCD will work and if anything is in the way it will get whacked.

If you don't want the body to arrive in one time step, just limit the max speed it can have.

If you would rather use ApplyForce/ApplyLinearImpulse, you could do something similar but you need to take into account the current speed of the body too. You might find this page helpful, it explains the rotation version of this but the principle is the same: http://www.iforce2d.net/b2dtut/rotate-to-angle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!