41 lines
1012 B
JavaScript
41 lines
1012 B
JavaScript
export class Vector2 {
|
|
constructor(x = 0, y = 0) {
|
|
this.x = x;
|
|
this.y = y;
|
|
}
|
|
// 向量加法
|
|
add(v) {
|
|
return new Vector2(this.x + v.x, this.y + v.y);
|
|
}
|
|
// 向量减法
|
|
subtract(v) {
|
|
return new Vector2(this.x - v.x, this.y - v.y);
|
|
}
|
|
// 向量缩放
|
|
scale(scalar) {
|
|
return new Vector2(this.x * scalar, this.y * scalar);
|
|
}
|
|
// 向量归一化
|
|
normalize() {
|
|
const len = this.length();
|
|
return len > 0 ? this.scale(1 / len) : new Vector2();
|
|
}
|
|
// 向量长度
|
|
length() {
|
|
return Math.sqrt(this.x * this.x + this.y * this.y);
|
|
}
|
|
// 计算两点间距离
|
|
distanceTo(v) {
|
|
return this.subtract(v).length();
|
|
}
|
|
// 克隆向量
|
|
clone() {
|
|
return new Vector2(this.x, this.y);
|
|
}
|
|
// 限制向量长度
|
|
clampLength(maxLength) {
|
|
const len = this.length();
|
|
return len > maxLength ? this.normalize().scale(maxLength) : this.clone();
|
|
}
|
|
}
|