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

源代码 2024-9-24 18:34:11 39 0 来自 中国
书名:代码本色:用编程模仿天然体系
作者: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 worldVerletPhysics2D physicsarticle p1article 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、运行结果

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

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

GMT+8, 2024-10-18 16:53, Processed in 0.158588 second(s), 32 queries.© 2003-2025 cbk Team.

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