Java Box2d车身不响应输入
我正在使用libgdx和box2d,我想让我的玩家的身体跳跃。当我尝试使用某些方法时,即使只是为了移动,也不会发生任何事情Java Box2d车身不响应输入,java,libgdx,box2d,gravity,Java,Libgdx,Box2d,Gravity,我正在使用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
//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`
}
}
没有任何事情发生,玩家的身体只是下降,直到它撞到一个静止的身体,每次我触摸屏幕,它只打印出“触摸”的字符串
更新
不确定这是否是它不工作的原因,我有两个类,一个用于渲染,一个用于更新。在update类上,我设置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
}
对于rendering类来说,相同的事情是,box2debugrenderer
在我的身体所在的位置分开
更新
我修复了这个问题,我的物理类连接到更新和渲染类,它引用了主类的create方法,我不理解,因为这是我为其他类的构造函数所做的
public void create(){
physics = new Physics(); //object for the Physics constructor.
}
问题是您使用的是以米为单位的box2d比例 所以你创造的盒子是(20米x20米),所以“300”的力不足以把它向上移动 要使用box2d,需要转换值 将所有box2d值除以“Wolld_TO_BOX”值刻度 这篇文章可能会有帮助 祝你好运 更新: 试着换个颜色
Gdx.input.justTouched()
到
因为JustTouched()方法只被调用一次(不是以连续的方式)你的jump()
,World.step(…)
,debugRender.render(…)
函数应该在render()
方法上,而createPlayer()
开启应该在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);
}
我试图将物体设置为5x5米,然后将力设置为900米,但同样的情况也会发生,你能设置物体的重量吗?你可以将物体的密度设置为fixtureDef:尝试类似的方法:fixtureDef.density=0.1查看我答案的更新,你正在调用Gdx.input.JustTouch(),只调用了一次是的,这就是我所做的,在我的render类中,我有自己的render方法,该方法与主类中的render方法相同。这也是我的步骤PhysicClass.world.step(1/60f,6,2)的值;您使用的值没有问题,只是确保方法在正确的位置。它们在正确的位置,如果不是因为这个原因,我会知道每次单击屏幕时我都会打印一条字符串。最后一件事是尝试:将唤醒值设置为true player.applyForceToCenter(0,300,true);同时降低玩家的密度。createFixture(形状,0.1f);希望它的工作,因为我得到的一切(:/
@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);
}