整合代码:一个简单的交互式弹簧

avatar
作者
筋斗云
阅读量:115

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

5.17 整合代码:一个简单的交互式弹簧

  • 对于Box2D,手动设置物体的位置会破坏物理模拟。在toxiclibs中并不存在这样的问题。如果要移动粒子的位置,我们可以直接设置它的x坐标和y坐标。但在设置之前,我们最好先调用lock()函数。

  • lock()函数的作用就是将物体锁在某个位置,等同于将Box2D物体的密度设成0。下面我将展示如何临时锁住一个粒子,然后移动它,最后将它解锁,让它继续参与物理模拟。假设你想在鼠标点击时移动一个粒子。

if (mousePressed) {     p2.lock(); 先锁住粒子,然后设置它的x坐标和y坐标,再对其解锁     p2.x = mouseX;     p2.y = mouseY;     p2.unlock(); } 
  • 在下面的示例程序中,我们将所有元素都放在一起,也就是通过弹簧将两个粒子连接在一起。其中的一个粒子被锁定在某个位置,另一个粒子在鼠标拖动时发生移动。注意,本例和示例代码3-11的效果是一样的。

2、示例

代码5-10 用toxiclibs实现简单的弹簧模拟

import toxi.physics2d.*; import toxi.physics2d.behaviors.*; import toxi.geom.*;  // Reference to physics world VerletPhysics2D physics;  Particle p1; Particle p2;  void setup() {   size(640,360);    // Initialize the physics   physics=new VerletPhysics2D();   physics.addBehavior(new GravityBehavior(new Vec2D(0,0.5)));    // Set the world's bounding box   physics.setWorldBounds(new Rect(0,0,width,height));      // Make two particles   p1 = new Particle(new Vec2D(width/2,20));   p2 = new Particle(new Vec2D(width/2+160,20));   // Lock one in place   p1.lock();    // Make a spring connecting both Particles   VerletSpring2D spring=new VerletSpring2D(p1,p2,160,0.01);    // Anything we make, we have to add into the physics world   physics.addParticle(p1);   physics.addParticle(p2);   physics.addSpring(spring); }  void draw() {    // Update the physics world   physics.update();    background(255);    // Draw a line between the particles   stroke(0);   strokeWeight(2);   line(p1.x,p1.y,p2.x,p2.y);    // Display the particles   p1.display();   p2.display();    // Move the second one according to the mouse   if (mousePressed) {     p2.lock();     p2.x = mouseX;     p2.y = mouseY;     p2.unlock();   }  } 

Particle.pde

class Particle extends VerletParticle2D {    Particle(Vec2D loc) {     super(loc);   }    // All we're doing really is adding a display() function to a VerletParticle   void display() {     fill(127);     stroke(0);     strokeWeight(2);     ellipse(x,y,32,32);   } } 

3、运行结果

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!