此篇博客均基于《代码本色》第一章所写。
前言
自然界中的物体概念(如,风、位置、速度等)都需要用两个变量来表示。如果是三维物体那就需要三个变量了,可见,向量在我们生活中无处不在。首先我们先了解一下PVector类中有哪些基本运算。
//这些运算在之后的写代码阶段会让给我们方便很多
实验效果
/
可以看到颜色随机生成的小球随鼠标移动而移动,在遇到边框或者与鼠标小于一定距离时候会反弹,但是仍然有像鼠标方向移动的趋势。
一些概念的运用:首先可以直观看出来的是向量的运用,其实向量也不难,我们可以将其看成两个不同方向单位矢量的合成,比如下面这样:
在进行计算的时候只需要将向量的x,y分别计算,然后结合到一起即可得到最终矢量。
实验过程
1、参考代码
1.1弹球程序,即小球遇到边框时候会反弹
1.2小球向鼠标方向移动
这里插入代码片
class Mover {
// The Mover tracks position, velocity, and acceleration
PVector position;
PVector velocity;
PVector acceleration; // The Mover's maximum speed
float topspeed;
Mover() {
// Start in the center
position = new PVector(width/2,height/2);
velocity = new PVector(0,0);
topspeed = 5;
}
void update() {
// Compute a vector that points from position to mouse
PVector mouse = new PVector(mouseX,mouseY);
PVector acceleration = PVector.sub(mouse,position); // Set magnitude of acceleration
acceleration.setMag(0.2); // Velocity changes according to acceleration
velocity.add(acceleration); // Limit the velocity by topspeed
velocity.limit(topspeed); // position changes by velocity
position.add(velocity);
}
void display() {
stroke(0);
strokeWeight(2);
fill(127);
ellipse(position.x,position.y,48,48);
}
}
Mover mover;
void setup() {
size(640,360);
mover = new Mover();
}
void draw() {
background(255); // Update the position
mover.update(); // Display the Mover
mover.display();
}
在上述代码参考的基础之上,我增加了颜色随机,会反弹两个功能
在Mover中初始化颜色,当然在前面也得声明一个color变量c
///
在display()中加入使得小球反弹的代码,其实就是改变它的速度方向,但是同时也得保证小球仍然有向鼠标方向移动的趋势
其实这一章东西不多,也不是很难,但是向量的运用在模拟自然系统中显得尤为重要,以上代码只是粗略地展示了向量的基本运用。