书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
目录
1.6 单位化向量
一、单位向量
计算向量的长度只是一个开始。长度计算函数引入了更多的向量运算,第一个就是单位化。单位化也称为正规化,正规化就是把某种事物变成“标准”或“常规”状态。
一个“标准”的向量就是长度为1的向量。因此,将一个向量单位化,就是使它的方向保持不变,但长度变为1,这样的向量称为单位向量。
由于单位向量描述了一个向量的方向,又不用关心长度,所以,获取一个向量的单位向量是非常有用的操作。
二、计算方法
对于一个给定的向量,它的单位向量(表示成)可以通过以下方法计算得到:
也就是说,要单位化一个向量,我们只需要将它的每个分量除以它的长度
三、向量的单位化
在PVector类中,我们这么实现向量的单位化:
void normalize() {
float m = mag();
if (m != 0) {
div(m);
}
}
四、示例
PVector location;
PVector velocity;
void setup() {
size(640,360);
}
void draw() {
//background(255);
PVector mouse = new PVector(mouseX,mouseY);
PVector center = new PVector(width / 2,height / 2);
mouse.sub(center);
mouse.normalize();
mouse.mult(150);
translate(width / 2,height / 2);
line(0,0,mouse.x,mouse.y);
}
class PVector {
float x;
float y;
PVector(float x_,float y_) {
x = x_;
y = y_;
}
void add(PVector v) {
x = x + v.x;
y = y + v.y;
}
void sub(PVector v) {
x = x - v.x;
y = y - v.y;
}
void mult(float n) {
x = x * n;
y = y * n;
}
void div(float n) {
x = x / n;
y = y / n;
}
float mag() {
return sqrt(x * x + y * y);
}
void normalize() {
float m = mag();
if(m != 0) {
div(m);
}
}
}