2022-04-10
在Processing语言中,提供了一种向量类,称作Pvector.
这个类中提供了若干种方法:部分方法的实现在 代码本色 书中有介绍。便于更深入理解其意义。
Methods
-
set()
Set the components of the vector -
random2D()
Make a new 2D unit vector with a random direction -
random3D()
Make a new 3D unit vector with a random direction -
fromAngle()
Make a new 2D unit vector from an angle -
copy()
Get a copy of the vector -
mag()
Calculate the magnitude of the vector -
magSq()
Calculate the magnitude of the vector, squared -
add()
Adds x, y, and z components to a vector, one vector to another, or two independent vectors -
sub()
Subtract x, y, and z components from a vector, one vector from another, or two independent vectors -
mult()
Multiply a vector by a scalar -
div()
Divide a vector by a scalar -
dist()
Calculate the distance between two points -
dot()
Calculate the dot product of two vectors -
cross()
Calculate and return the cross product -
normalize()
Normalize the vector to a length of 1 -
limit()
Limit the magnitude of the vector -
setMag()
Set the magnitude of the vector -
heading()
Calculate the angle of rotation for this vector -
rotate()
Rotate the vector by an angle (2D only) -
lerp()
Linear interpolate the vector to another vector -
angleBetween()
Calculate and return the angle between two vectors -
array()
Return a representation of the vector as a float array
以下是向量做加法的示例:
需要注意的是,向量不可以直接用+、-这样的符号运算。而是需要内置的相关方法。
PVector v1, v2;
void setup() {
noLoop();
v1 = new PVector(40, 20);
v2 = new PVector(25, 50);
}
void draw() {
ellipse(v1.x, v1.y, 12, 12);
ellipse(v2.x, v2.y, 12, 12);
v2.add(v1);
ellipse(v2.x, v2.y, 24, 24);
}
image.png
注释2:
在 代码本色 一书中,使用Pvector类来实现物理的移动,就是设计了具有二维位置、具有二维方向的速度和加速度。
- 基本的知识:速度由加速度累加而得,移动距离即最终位置由速度累加而得。是积分的概念。
例程的运行效果是使圆形跟随鼠标运动。
注释3:
这小圆形在鼠标静止时一直在运动。并未停下来。这个是什么原因?
需思考。
image.png
程序首先使用Pvector定义了一个Mover类:
初始位置在窗口中心,速度为0,并设计了速度上限。否则因为具有加速度,速度会一直增加。
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
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);
}
}
主程序比较简洁:
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
// A Mover object
Mover mover;
void setup() {
size(640,360);
mover = new Mover();
}
void draw() {
background(255);
// Update the position
mover.update();
// Display the Mover
mover.display();
}