我在LibGDX中使用Box2D来移动我的玩家。世界引力设置为(0f,0f)。但是,我的代码感觉很长而且生硬,我觉得我可以重构它以更有效地实现它,但我不确定如何。有什么我可以改进的吗?
private void playerMovement() {
if(Gdx.input.isKeyPressed(Input.Keys.W)){
body.setLinearVelocity(new Vector2(0f,30f));
}if(Gdx.input.isKeyPressed(Input.Keys.S)){
body.setLinearVelocity(new Vector2(0f, -30f));
}if(Gdx.input.isKeyPressed(Input.Keys.A)){
body.setLinearVelocity(new Vector2(-30f, 0f));
}if(Gdx.input.isKeyPressed(Input.Keys.D)){
body.setLinearVelocity(new Vector2(30f,0f));
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.A)){
body.setLinearVelocity(new Vector2(-30f, 30f));
}if(Gdx.input.isKeyPressed(Input.Keys.W) && Gdx.input.isKeyPressed(Input.Keys.D)){
body.setLinearVelocity(new Vector2(30f, 30f));
}if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.A)){
body.setLinearVelocity(new Vector2(-30f, -30f));
}if(Gdx.input.isKeyPressed(Input.Keys.S) && Gdx.input.isKeyPressed(Input.Keys.D)){
body.setLinearVelocity(new Vector2(30f, -30f));
}else if(!Gdx.input.isKeyPressed(Input.Keys.ANY_KEY)){
body.setLinearVelocity(new Vector2(0f,0f));
}
}
这种方法是否适合使用Box2D进行平稳移动?世界引力设置为(0f,0f)。不确定我是否可以编写更少的代码。
答案 0 :(得分:0)
更有效的方式。
var descendants = document.getElementById('tbody').getElementsByTagName("*");
for(var i = 0; i < descendants.length; i++) {
descendants[i].classList.remove('cl1');
descendants[i].classList.add('cl2');
}
答案 1 :(得分:0)
PlayerMovement的最终代码,如果有人想要使用它。我不得不修改答案的代码,因为有些错误,但现在它可以正常工作。
private void playerMovement() {
float speed = 30f;
if(Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) {
if(Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
body.setLinearVelocity(-speed,speed);
}else if(Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
body.setLinearVelocity(speed, speed);
}else
body.setLinearVelocity(0f, speed);
}else if(Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
if(Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
body.setLinearVelocity(-speed, -speed);
}else if(Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
body.setLinearVelocity(speed, -speed);
}else
body.setLinearVelocity(0f, -speed);
}else if(Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
body.setLinearVelocity(-speed, 0f);
}else if(Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
body.setLinearVelocity(speed, 0f);
}else
body.setLinearVelocity(0f, 0f);
}