简体   繁体   中英

Box2d setTransform

Set the scene: • Our environment: LibGdx Android & iOS //If you don't know LibGdx, it's fine, just know that this program is being build for iOS and Android

• Our screen has nothing on it, just a Box2d Circle

Okay, so, what do I need to do? I need to make my Box2d Circle to "teleport" to where the screen is tapped... but I need it to have some velocity so if it collides w/ something else it will throw the other object out of its way.

I am currently using body.setTransform() but I have no velocity and people say it is very buggy.

How can I do this? Thank you!

The setTransform method is not buggy itself. It can cause some troubles because of ignoring physics which can appear when :

  • using joints - joints provide some constraint and this "violent" change can make bodies behave weird
  • collision exists - because the transformed body can be "pushed" into other body

The situation you are describing is totally typical situation when setTransform is being used and I see no reason here to be afraid of it. You don't need any velocity here also.


However, if you decide to change the "teleporting" mechanism to applying the velocity to move object to the world point you should:

  • calculate velocity vector by subtracting target position and body position

     Vector2 velocity = target.sub( body.getPosition() ) ); //where target is Vector2 of touched point 
  • limit the velocity to some maximum I guess if you need to (this is optional)

     //optional velocity.nor(); velocity.mul( MAX_VALUE ); //MAX_VALUE is a float 
  • set the velocity to the body

     body.setLinearVelocity( velocity ); 
  • add to main loop (render method) check if the body is in target position (or in some range - due to precision there is small chance that it will precisely at the target if you will limit the velocity - if not I guess it should be in the target position after one iteration of world.update() )

     if( body.getPosition().sub( target ).len() < SOME_PRECISION ) { body.setLinearVelocity( new Vector2(0, 0) ); } 

You can also take a look at Box2D MouseJoint although I've been never using this and cannot provide any hint here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM