我在使用JBox2D时遇到了一些问题。据我所知,我已经创建了一个球和世界以及所有东西,但是当我调用world.step()方法时,它并没有使球从重力中掉落。
这是我的对象创建:
package objects;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.lwjgl.opengl.GL11;
import util.GLColor;
import util.Location;
import util.Size;
public class PlayerCircle extends DefaultObject{
GLColor c = new GLColor(25,255,255);
public PlayerCircle(Location l,Size s){
super(l,s);
load(l.getX(),l.getY());
}
BodyDef bd = new BodyDef();
FixtureDef fd = new FixtureDef();
public static CircleShape cd = new CircleShape();
public void load(double x, double y){
bd.type = BodyType.DYNAMIC;
// bd.position = new Vec2(0.0f, -10.0f);
cd.m_radius = s.getRadius()/Main.Main.scaleX;
//cd.m_p.set((float)x/Main.Main.scaleX,(float)y/Main.Main.scaleY);
bd.position = new Vec2((float)x/Main.Main.scaleX,(float)y/Main.Main.scaleY);
fd.friction = .1f;
fd.density = 2f;
fd.shape = cd;
Main.Main.getWorld().createBody(bd).createFixture(fd);
// bd.allowSleep = false;
}
}
以下是主循环所在的代码:
public void run() throws LWJGLException, InterruptedException{
Vec2 gravity = new Vec2(2f, -.1f);
world = new World(gravity, true);
Display.setDisplayMode(new DisplayMode(900,700));
Display.create();
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, scaleX, 0, scaleY, 1, -1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
level = new Level1();
level.load();
level.start();
float tempStep = 1.0f/60.0f;
int VI = 6;
int POSI = 2;
int a = 0;
while(!done){
//System.out.println(world.getContactCount() + " "+world.getGravity().x);
world.step(tempStep, VI, POSI);
Display.update();
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
logic();
if (Display.isVisible() || Display.isDirty()) {
render();
}
if(Display.isCloseRequested()){
done = true;
}
Thread.sleep(1);
}
}
}
测试班
package test;
import objects.PlayerCircle;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;
import util.Location;
import util.Size;
public class Test {
static Vec2 gravity = new Vec2(2f, -.5f);
static float tempStep = 1.0f/60.0f;
static int VI = 6;
static int POSI = 2;
public static World world = new World(gravity,true);
public static void main(String args[]){
PlayerCircle pc = new PlayerCircle(new Location(400,5000),new Size(10));
while(true){
world.step(tempStep, VI, POSI);
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(pc.bd.position.y);
}
}
}
打印结果
7.142857
7.142857
7.142857
7.142857
7.142857
7.142857
7.142857
7.142857
7.142857
7.142857
最佳答案
从Body对象而不是BodyDef对象获取y位置。
为此,请存储Main.Main.getWorld()。createBody(bd)返回的Body对象,并通过pc.yourBodyVariableNameHere.m_xf.position.y访问其位置。