书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
4.8 用继承实现粒子类
在粒子类上实践继承的用法。
class Particle {
PVector position;
PVector velocity;
PVector acceleration;
Particle(PVector l) {
acceleration = new PVector(0, 0.05);
velocity = new PVector(random(-1, 1), random(-1, 0));
position = l.get();
}
void run() {
update();
display();
}
void update() {
velocity.add(acceleration);
position.add(velocity);
}
void display() {
fill(0);
ellipse(position.x, position.y, 12, 12);
}
}
继承Particle类。Confetti类会从Particle类中继承所有的变量和方法,我们还要为它定义自己的构造函数,并通过super()函数调用父类的构造函数。
class Confetti extends Particle {
我们可以在这里加入Confetti专有的变量
Confetti(PVector l) {
super(l);
}
这里没有update()的实现,因为我们从父类中继承了update()函数
void display() { 覆盖display方法
rectMode(CENTER);
fill(175);
stroke(0);
rect(location.x, location.y, 8, 8);
}
}
可以把本例实现得稍微复杂一些:让Confetti粒子像苍蝇一样在空中飞动旋转。
void display() {
float theta = map(location.x,0,width,0,TWO_PI*2);
rectMode(CENTER);
fill(0,lifespan);
stroke(0,lifespan);
pushMatrix();
translate(location.x, location.y); 使用rotate()函数之前,我们必须熟悉变换。如果想了解rotate(theta);
rect(0,0,8,8);
popMatrix();
}
4.9 多态基础