简体   繁体   中英

limit linear velocity of body android andengine box2d

im moving a ball with a box body and at each collision/contact im increasing the linearvelocity by factor 1.1. the velocity increases but im not able to limit the velocity

code:

public static final FixtureDef _BALL_FIXTURE_DEF=PhysicsFactory.createFixtureDef(0, 1.0f, 0.0f, false, _CATEGORYBIT_BALL, _MASKBITS_BALL, (short)0);
_ballCoreBody = PhysicsFactory.createCircleBody(_physicsWorld, _ballCore, BodyType.DynamicBody, _BALL_FIXTURE_DEF);
_ballCoreBody.setAngularDamping(0);
_ballCoreBody.setLinearDamping(0);
_ballCoreBody.setActive(true);
_ballCoreBody.setBullet(true);
_ballCoreBody.setGravityScale(0);
this._scene.attachChild(_ballCore);
this._physicsWorld.registerPhysicsConnector(new PhysicsConnector(_ballCore, _ballCoreBody));

inside contactListener

if(x1.getBody().getLinearVelocity().x<15.0f && x1.getBody().getLinearVelocity().y<15.0f)
x1.getBody().setLinearVelocity(new Vector2(x1.getBody().getLinearVelocity().x*1.2f, x1.getBody().getLinearVelocity().y*1.2f));
else
x1.getBody().setLinearVelocity(new Vector2(x1.getBody().getLinearVelocity().x/1.1f, x1.getBody().getLinearVelocity().y/1.1f));

how do i achieve this?

From what I can see you are not capping the velocity at all in your code. What is inside the contact listener is that it will increase the speed by factor 1.2 when the velocity is below 15.0 and by factor 1.1 there after, so it will constantly speed up with every collision. This might be more suitable, give it a go (not tested the code through, so might need adjusting):

float xVel = x1.getBody().getLinearVelocity().x;
float yVel = x1.getBody().getLinearVelocity().y;

//if you want to be sure the speed is capped in all directions evenly you need to find
//the speed in the direction and then cap it.
bool isBelowMaxVel = ( xVel * xVel + yVel, * yVel ) < 225.0f; //15 * 15 = 225 // this is to avoid using a square root

if( isBelowMaxVel ) // only increase speed if max not reached
{
    x1.getBody().setLinearVelocity(new Vector2( xVel * 1.1f, yVel * 1.1f ));
}

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