大家晚上好。 我请求你的帮助!我发现了Box2D,但我已经在努力解决一些问题:
我的引力是逆转的,我不明白为什么。 而我的第二个问题是我无法以调试的方式绘制它。 我不得不手动绘制它以实际看到的东西。
这是一个可以使用的代码示例!
package tests;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import engine.jbox2d.collision.shapes.CircleShape;
import engine.jbox2d.collision.shapes.PolygonShape;
import engine.jbox2d.common.Vec2;
import engine.jbox2d.dynamics.Body;
import engine.jbox2d.dynamics.BodyDef;
import engine.jbox2d.dynamics.BodyType;
import engine.jbox2d.dynamics.FixtureDef;
import engine.jbox2d.dynamics.World;
public class JBox2DTest extends JPanel
{
private static final long serialVersionUID = 7173873195721096625L;
// model
private World world;
private Ball ball;
public JBox2DTest()
{
// Création du monde
world = new World(new Vec2(0.0f, -9.81f));
// Création d'un sol
new Ground(world);
// Création d'une balle
this.ball = new Ball(world);
//Création de la frame
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
//Loop
Timer simulationTimer = new Timer(10, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
world.step(1.0f / 60.0f, 6, 2);
repaint();
}
});
simulationTimer.start();
}
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
ball.draw((Graphics2D) g);
}
public static void main(String[] args)
{
new JBox2DTest();
}
}
class Ground
{
Body body;
public Ground(World world)
{
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(0.0f, -10.0f);
body = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(800.0f, 10);
body.createFixture(groundBox, 0.0f);
}
}
class Ball
{
private Body body;
public Ball(World world)
{
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC; // Sujet aux forces
bodyDef.position.set(800/2, 600/2);
this.body = world.createBody(bodyDef);
CircleShape dynamicCirle = new CircleShape();
dynamicCirle.setRadius(10f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCirle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.3f;
body.createFixture(fixtureDef);
}
public void draw(Graphics2D g2d)
{
g2d.setColor(Color.RED);
Vec2 ballPos = body.getPosition();
float ballRadius = body.getFixtureList().getShape().getRadius();
g2d.drawOval(
(int) (ballPos.x - ballRadius),
(int) (ballPos.y - ballRadius),
(int) (ballRadius * 2),
(int) (ballRadius * 2)
);
}
}
非常感谢你的帮助! 最好的祝福, Alann
答案 0 :(得分:0)
这显然取决于你正在使用的Box2D的实现。您的版本可能会反转重力:
world = new World(new Vec2(0.0f, -9.81f));
应该没有减号:
world = new World(new Vec2(0.0f, 9.81f));