java - How to move apply force to bodies in a top down game?
问题描述
So I am making a top down game where the player moves using WASD keys. For this I use
if (Gdx.input.isKeyPressed(Input.Keys.S) && b2dBody.getLinearVelocity().y >= -0.8) {
b2dBody.applyLinearImpulse(new Vector2(0, -PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.W) && b2dBody.getLinearVelocity().y <= 0.8) {
b2dBody.applyLinearImpulse(new Vector2(0f, PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.A) && b2dBody.getLinearVelocity().x >= -0.8) {
b2dBody.applyLinearImpulse(new Vector2(-PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.D) && b2dBody.getLinearVelocity().x <= 0.8) {
b2dBody.applyLinearImpulse(new Vector2(PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
}
But because the gravity is set to 0 world = new World(new Vector2(0, 0), true);
the body doesn't stop. I was wondering if there was a way to keep the gravity the same while making the body stop after after a while? Thanks in advance.
解决方案
创建 box2d 主体时,您可以设置用于创建主体的BodyDeflinearDamping
对象的值。
这个值总是会在物体移动时减慢物体的速度(例如,当应用线性脉冲时)。
你可以像这样使用它:
BodyDef bodyDef = new BodyDef();
//set other body values
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(42f, 42f);
bodyDef.angle = 0f;
//...
bodyDef.linearDamping = 10f; // this will make the body slow down when moving
//create the body
Body body = world.createBody(bodyDef);
// TODO move the body arround and it will automatically slow down
推荐阅读
- docker - Docker 容器不响应请求
- laravel - POST请求的Laravel分页
- python - 将附加属性传递给 django-filter
- python - 为什么 numpy.linarg.solve 给出不同的答案?
- javascript - 幻灯片隐藏和显示文本
- r - 在 R 中聚合具有不同类别列的数据
- c# - 将具有多种日期时间格式的 JSON 响应解析为 c# 对象
- java - 在 Java 中使用 GSON 解析 JSON,具有多个具有非重复值的根键
- flutter - Flutter:部分图片横向显示(旋转90度)
- python - 更新止损单 API Interactive Brokers Python