固定的Box2D对象

5个月前 (12-13) 0 点赞 0 收藏 0 评论 11 已阅读

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录

5.8 固定的Box2D对象

  在上面的例子中,盒子对象首先出现在鼠标所在的位置,之后随着Box2D中默认的重力作用下落。假如我们想在Box2D中放置一些固定的边界,这些边界能够阻挡盒子物体运动路径(如下图所示),该怎么实现?

1、锁定

  在Box2D中,我们可以简单地将物体(包括所有已连接的形状)锁定在某个位置。只要把BodyDef对象的type属性设为STATIC。

BodyDef bd = new BodyDef();
bd.type = BodyType.STATIC; 定义的type属性一旦被设为STATIC,物体就被锁定在某个位置

  我们可以在上面的盒子示例程序中加入这个特性,只需要添加一个Boundary类,并且为每个边界分别创建Box2D物体。

2、示例

  示例代码5-2 带有撞击边界的盒子下落模拟

// A fixed boundary class
class Boundary {

  // A boundary is a simple rectangle with x,y,width,and height
  float x;
  float y;
  float w;
  float h;
  
  // But we also have to make a body for box2d to know about it
  Body b;

  Boundary(float x_,float y_, float w_, float h_) {
    x = x_;
    y = y_;
    w = w_;
    h = h_;

    // Define the polygon
    PolygonShape ps = new PolygonShape();
    // Figure out the box2d coordinates
    float box2dW = box2d.scalarPixelsToWorld(w/2);
    float box2dH = box2d.scalarPixelsToWorld(h/2);
    // We're just a box
    ps.setAsBox(box2dW, box2dH);


    // Create the body
    BodyDef bd = new BodyDef();
    bd.type = BodyType.STATIC;
    bd.position.set(box2d.coordPixelsToWorld(x,y));
    b = box2d.createBody(bd);
    
    // Attached the shape to the body using a Fixture
    b.createFixture(ps,1);
  }

  // Draw the boundary, if it were at an angle we'd have to do something fancier
  void display() {
    fill(0);
    stroke(0);
    rectMode(CENTER);
    rect(x,y,w,h);
  }

}

3、运行结果


固定的Box2D对象

本文收录在
0评论

登录

忘记密码 ?

切换登录

注册