有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用box2d构造和绘制漂亮的绳子

我用RevoluteJointRopeJoint在box2d中创建了一条绳子,但我有几个问题:

  1. 有时,最后一段会旋转,看起来好像是从绳子上断开的
  2. 怎么画这个东西?我根据每个链接的大小创建一个纹理。如果绳子没有移动,看起来不错,但是一旦绳子移动,不同的链环开始轻微旋转,你就会看到链环之间的间隙

代码:

private void createChain(World world, Body anchorBody) {
  Body previousBody = anchorBody;

  FixtureDef fixtureDef = new FixtureDef();

  PolygonShape robeLinkShape = new PolygonShape();
  robeLinkShape.setAsBox(4 / PPM, 8 / PPM);
  fixtureDef.shape = robeLinkShape;
  fixtureDef.density = 0.1f;
  //    fixtureDef.friction = 1.0f;
  fixtureDef.restitution = 0.1f;
  fixtureDef.filter.maskBits = Box2DConst.BIT_PLAYER;
  fixtureDef.filter.categoryBits = Box2DConst.BIT_GROUND;

  float mapX = anchorBody.getPosition().x * PPM;
  float mapY = anchorBody.getPosition().y * PPM;

  BodyDef bodyDef = new BodyDef();
  bodyDef.angularDamping = 1.0f;
  bodyDef.linearDamping = 1.0f;

  //create rope
  for (int i = 0; i < 10; i++) {
    Float robeX = mapX / PPM;
    Float robeY = (mapY - (i * 16)) / PPM;
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(robeX, robeY);

    final Body link = world.createBody(bodyDef);
    link.createFixture(fixtureDef);

    RevoluteJointDef jointDef = new RevoluteJointDef();
    jointDef.initialize(previousBody, link, new Vector2(robeX, robeY));

    //don't need the rope to collide itself
    jointDef.collideConnected = false;
    jointDef.enableLimit = false;

    // because we don't collide with other bodies in the rope, limit rotation to keep the rope bodies from rotating too much.
    jointDef.lowerAngle = -5.0f * MathUtils.degreesToRadians;
    jointDef.upperAngle = 5.0f * MathUtils.degreesToRadians;
    world.createJoint(jointDef);

    links.add(link);
    previousBody = link;
  }

  RopeJointDef ropeJointDef = new RopeJointDef();
  ropeJointDef.localAnchorB.set(0, 0);
  ropeJointDef.maxLength = 90.0f;
  ropeJointDef.bodyB = previousBody;
  ropeJointDef.bodyA = links.get(0);
  ropeJointDef.collideConnected = false;
  world.createJoint(ropeJointDef);
}

public void draw(final SpriteBatch batch) {
  Texture texture = FipiGame.res.get("rope");
  batch.begin();
  for (Body link : links) {
    float x = (link.getPosition().x * PPM) - 4;
    float y = (link.getPosition().y * PPM) - 8;

    float angleDeg = MathUtils.radiansToDegrees * link.getAngle();
    batch.draw(texture, x, y, 0, 0, texture.getWidth(), texture.getHeight(), 1f, 1f, angleDeg, 0,   0,
             texture.getWidth(), texture.getHeight(), false, false);
   }
batch.end();
}

共 (1) 个答案

  1. # 1 楼答案

    不要基于身体位置和旋转进行绘制:通过旋转关节位置(世界空间中的锚定点和锚定点的中点)循环创建一组点。然后画你的精灵,让他们连接这些位置。这会有点不准确,因为它不会与刚体的位置完全对齐,但看起来应该没问题