带有角速度的振荡

2022-05-01  本文已影响0人  大龙10

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

3.7 带有角速度的振荡

1、简谐运动2

  一个以弧度为单位的圆(一个圆周为2π,即:360度=2π),

2、Oscillator(振荡者)类

3、示例代码3-7

示例代码3-7 Oscillator对象

// An array of objects
Oscillator[] oscillators = new Oscillator[10];

void setup()  {   
  size(640,360);  
  smooth();  
  // Initialize all objects
  for (int i = 0; i < oscillators.length; i++) {
    oscillators[i] = new Oscillator();
  }
  background(255);  
}   

void draw() {     
  background(255);  
  // Run all objects
  for (int i = 0; i < oscillators.length; i++) {
    oscillators[i].oscillate();
    oscillators[i].display();
  }
}   

Oscillator.pde

class Oscillator {   

  PVector angle;
  PVector velocity;
  PVector amplitude;
  color c;

  Oscillator() {   
    angle = new PVector();
    velocity = new PVector(random(-0.05, 0.05), random(-0.05, 0.05));
    amplitude = new PVector(random(20,width/2), random(20,height/2));
    c = color(random(255),random(255),random(255));
  }   

  void oscillate() {
    angle.add(velocity);
  }   

  void display() {   

    float x = sin(angle.x)*amplitude.x;
    float y = sin(angle.y)*amplitude.y;

    pushMatrix();
    translate(width/2, height/2);
    stroke(0);
    strokeWeight(2);
    fill(c);
    line(0, 0, x, y);  
    ellipse(x, y, 32, 32);  
    popMatrix();
  }
}   

4、运行效果

上一篇 下一篇

猜你喜欢

热点阅读