Mr.*_*lis 2 javascript processing p5.js
dist() 计算两个点之间的距离,但是我想计算5个点之间的距离(一个圆点与一个矩形中的四个点之间的距离(每个角都有一个点))我该怎么做?
intersects(other){
let di = dist(this.x, this.y, other.x, other.y)
let di2 = dist(this.x, this.y, other.x + 80, other.y)
let di3 = dist(this.x, this.y, other.x, other.y + 150)
let di4 = dist(this.x, this.y, other.x + 80, other.y + 150)
if (di && di2 && di3 && di4 <= this.r) {
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我试图对其进行硬编码,但是if函数仅使用“ di4”
如果要验证所有距离是否都低于某个阈值,则必须将所有值与参考距离进行比较,并通过&&以下方法将结果连接起来:
if (di <= this.r && di2 <= this.r && di3 <= this.r && di4 <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
如果要验证任何距离是否低于某个阈值,则必须将所有值与参考距离进行比较,并通过||以下方法将结果连接起来:
if (di <= this.r || di2 <= this.r || di3 <= this.r || di4 <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
如果要获取最大值列表,则可以使用该max()函数。如果所有距离都在下面,则等于评估this.r:
if (max([di, di2, di3, di4]) <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
如果要获取最小值列表,则可以使用该min()函数。如果以下任何距离均等于评估this.r:
if (min([di, di2, di3, di4]) <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
注意,表达式
Run Code Online (Sandbox Code Playgroud)di && di2 && di3 && di4 <= this.r
不执行您期望的操作。仅d14与进行比较this.r。其他术语的评估结果是true它们是否未定义且值不等于0.0。
这意味着该表达式可以读取为di != 0 && di2 != 0 && di3 != 0 && di4 <= this.r
但是请注意,如果要验证圆是否完全在矩形内,则必须验证圆到每一边(而不是拐角点)的距离是否大于(而不是低于)半径范围:
intersects(other){
let di = this.x - other.x; // distance to the left
let di2 = other.x + 80 - this.x; // distance to the right
let di3 = this.y - other.y; // distance to the top
let di4 = other.y + 150 - this.y; // distance to the bottom
if (di >= this.r && di2 >= this.r && di3 >= this.r && di4 >= this.r) {
return false;
} else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您也想验证到矩形中心的距离,则必须通过来计算到中心的距离dist()。
因此,如果您要验证圆是否碰到了矩形的中心点或矩形的任意边,则必须检查是否所有距离都在半径以下
let di = this.x - other.x; // distance to the left
let di2 = other.x + 80 - this.x; // distance to the right
let di3 = this.y - other.y; // distance to the top
let di4 = other.y + 150 - this.y; // distance to the bottom
// distance to the center point
let di5 = dist(this.x, this.y, other.x + 80/2, other.y + 150/2);
if (di <= this.r || di2 <= this.r || di3 <= this.r && di4 <= this.r && di5 <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
要么
if (min([di, di2, di3, di4, di5]) <= this.r) {
// [...]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |