【问题标题】:Box2d body not responding to inputsBox2d 身体不响应输入
【发布时间】:2015-10-27 15:15:32
【问题描述】:

我正在使用 libgdx 和 box2d,我想让我的玩家的身体跳跃。当我尝试使用某些方法时,即使只是为了移动,也没有任何反应。

//gravity Vector2
Vector2 Gravity = new Vector2(0,-9.8);
//Box2d World
World world = New World(gravity);

//then I created my player body
public void createPlayer(){
    BodyDef def = new BodyDef();
    def.type = BodyDef.BodyType.DynamicBody;
    def.fixedRotation = true;
    def.position.set(80, 200);
    player = world.createBody(def);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(20, 20);
    player.createFixture(shape, 1f);
    shape.dispose();
}

//this is the jump method
public void jump(){
    if(Gdx.input.justTouched() == true) {
        player.applyForceToCenter(0, 900, false);
        System.out.println("touched");//to make sure the touch is working`
    }
}

什么都没有发生,玩家的身体只是下落,直到它撞到一个静态的身体,每次我触摸屏幕时它只会打印出“触摸”的字符串。

更新

不确定这是否是它不起作用的原因,我有两个类,一个用于渲染,一个用于更新。在更新类上,我设置了 world.step() 而不是直接设置到我的身体所在的类。

//class for updating

public void update(float deltaTime){
    physics.world.step(1 / 60f, 6, 2);
    physics.jump(); //calling jump method from Physics class
}

渲染类也是一样,Box2dDebugRenderer 在我的身体所在的地方是分开的

更新

我解决了这个问题,连接到 Update 和 Render 类的物理类引用了主类的 create 方法,我不明白,因为这是我为其他类的构造函数所做的。

public void create(){
    physics = new Physics(); //object for the Physics constructor.
}

【问题讨论】:

    标签: java libgdx box2d gravity


    【解决方案1】:

    问题是您正在使用以米为单位的 box2d 比例 所以你创造的盒子是(20米x 20米)所以“300”的力量不足以将它向上移动 要使用 box2d,您需要转换您的值

    将所有 box2d 值除以“WOLRD_TO_BOX”值比例

    这篇文章可能对你有帮助

    Libgdx Box2D pixel to meter conversion?

    祝你好运

    更新:

    尝试改变

    Gdx.input.justTouched() 
    

    到

    Gdx.input.isTouched()
    

    因为 JustTouched() 方法只被调用一次(不是以继续的方式)

    【讨论】:

    • 我尝试将身体设置为 5x5 米,然后将力设置为 900,但同样的事情发生了,你也可以设置身体的重量吗?
    • 你可以把body的密度放在fixtureDef中:试试这样的:fixtureDef.density = 0.1f
    • 查看我的答案的更新,您正在调用 Gdx.input.justTouched(),它只被调用一次
    【解决方案2】:

    您的 jump() 、 World.step(...) 、 debugRender.render(...) 函数应该在 render() 方法上,createPlayer() on 应该在 create() 方法上

     @Override
     public void create() {
            createPlayer()
    
     }
    
     @Override
     public void render() {
        //OpenGL settings
         Gdx.gl.glClearColor(0, 0, 0, 1);
         Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    
         world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
         jump();
         debugRendrer.render(world, camera.combined);
    }
    

    【讨论】:

    • 是的,这就是我所做的,在我的渲染类上,我有自己的渲染方法,它转到主类的渲染方法,我的更新方法也是如此。
    • 这也是我的步的值,physicsClass.world.step(1 / 60f, 6, 2);
    • 你使用的值没有问题,只要确保方法在正确的地方
    • 它们在正确的位置,如果不是因为每次单击屏幕我都会打印出一个字符串
    • 最后一件事:将唤醒值设置为 true player.applyForceToCenter(0, 300, true);并降低你的密度 player.createFixture(shape, 0.1f);希望它的工作能成就我所得到的一切(:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多