如何在p5js中获取单个像素的颜色
how to get the color of a single pixel in p5js
我正在尝试获取玩家下方像素的颜色,如果它是蓝色,我会阻止他们掉下来。由于某种原因,它检测到颜色,但 if 语句即使匹配也不会运行。这是代码:
gravity(){
if (this.y <= 400 - this.scale){
let gc = get(this.x, this.y + 25);
print(gc);
if (gc == [0, 0, 255, 255]){
this.canGravity = false;
}
else {
this.canGravity = true;
}
if (this.canGravity == true){
this.y += 2;
}
}
}
你非常接近,你的问题是相等性检查。
看看下面的例子:
let first = [1, 2];
let second = [1, 2];
console.log(first === second); // false;
检查 JavaScript 中两个数组是否相等的最佳方法是遍历每个元素并执行比较,因此您的示例可能如下所示:
if (arraysEqual(gc, [0, 0, 255, 255])) {
this.canGravity = false;
}
...
function arraysEqual(arr1, arr2) {
return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
}
或者更简单的方案:
if (gc[0] === 0 && gc[1] === 0 && gc[2] === 255 && gc[3] === 255) {
...
}
我正在尝试获取玩家下方像素的颜色,如果它是蓝色,我会阻止他们掉下来。由于某种原因,它检测到颜色,但 if 语句即使匹配也不会运行。这是代码:
gravity(){
if (this.y <= 400 - this.scale){
let gc = get(this.x, this.y + 25);
print(gc);
if (gc == [0, 0, 255, 255]){
this.canGravity = false;
}
else {
this.canGravity = true;
}
if (this.canGravity == true){
this.y += 2;
}
}
}
你非常接近,你的问题是相等性检查。
看看下面的例子:
let first = [1, 2];
let second = [1, 2];
console.log(first === second); // false;
检查 JavaScript 中两个数组是否相等的最佳方法是遍历每个元素并执行比较,因此您的示例可能如下所示:
if (arraysEqual(gc, [0, 0, 255, 255])) {
this.canGravity = false;
}
...
function arraysEqual(arr1, arr2) {
return arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
}
或者更简单的方案:
if (gc[0] === 0 && gc[1] === 0 && gc[2] === 255 && gc[3] === 255) {
...
}