固定的Box2D对象

分享
手机游戏开发者 2024-9-9 00:37:50 67 0 来自 中国
书名:代码本色:用编程模拟自然体系
作者: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 classclass 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、运行效果

您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-19 11:59, Processed in 0.189308 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表