全局变量"x"不存在,处理3.2.3
Global variable "x" does not exist, Processing 3.2.3
当我遇到无法找到解决方案的错误时,我开始在 Processing 中编码。
代码:
void setup(){
size(640,360);
}
int scl = 20;
void draw(){
background(250);
drawGrid(scl);
makeObject(0,0,20,20);
}
void drawGrid(float size){
for(int v=0;v<640/20;v++){
for(int h=0;h<360/20;h++){
rect(h*size,v*size,size,size);
}
}
}
void makeObject(int obX,int obY,int obHeight,int obWidth){
this.x = obX;
this.y = obY;
this.obH = obHeight;
this.obW = obWidth;
rect(this.x,this.y,this.obH,this.obW);
}
错误是:'The global variable "x" does not exist'、'The global variable "y" does not exist'等等。
请帮助
好吧,你的错误说明了一切:你正在使用一个 x
变量,但你从未声明它。
让我猜猜:您来自 Java脚本背景?您的 makeObject()
函数看起来像 JavaScript 构造函数,但这根本不是对象在 Java.
中的工作方式
在Java中,你必须定义一个class
,然后声明你要使用的变量。像这样:
class MyObject{
float x;
float y;
float obH;
float obW;
public MyObject(float obX, float obY, float obHeight, float obWidth){
this.x = obX;
this.y = obY;
this.obH = obHeight;
this.obW = obWidth;
}
}
然后您可以向该 class 添加函数,例如使用这些变量绘制矩形的 drawMe()
函数。
但是,我不确定您为什么要尝试创建一个对象,因为您实际上从未使用过您创建的对象。您可以直接使用参数:
void makeObject(int obX,int obY,int obHeight,int obWidth){
rect(obX, obY, obHeight, obWidth);
}
当我遇到无法找到解决方案的错误时,我开始在 Processing 中编码。
代码:
void setup(){
size(640,360);
}
int scl = 20;
void draw(){
background(250);
drawGrid(scl);
makeObject(0,0,20,20);
}
void drawGrid(float size){
for(int v=0;v<640/20;v++){
for(int h=0;h<360/20;h++){
rect(h*size,v*size,size,size);
}
}
}
void makeObject(int obX,int obY,int obHeight,int obWidth){
this.x = obX;
this.y = obY;
this.obH = obHeight;
this.obW = obWidth;
rect(this.x,this.y,this.obH,this.obW);
}
错误是:'The global variable "x" does not exist'、'The global variable "y" does not exist'等等。 请帮助
好吧,你的错误说明了一切:你正在使用一个 x
变量,但你从未声明它。
让我猜猜:您来自 Java脚本背景?您的 makeObject()
函数看起来像 JavaScript 构造函数,但这根本不是对象在 Java.
在Java中,你必须定义一个class
,然后声明你要使用的变量。像这样:
class MyObject{
float x;
float y;
float obH;
float obW;
public MyObject(float obX, float obY, float obHeight, float obWidth){
this.x = obX;
this.y = obY;
this.obH = obHeight;
this.obW = obWidth;
}
}
然后您可以向该 class 添加函数,例如使用这些变量绘制矩形的 drawMe()
函数。
但是,我不确定您为什么要尝试创建一个对象,因为您实际上从未使用过您创建的对象。您可以直接使用参数:
void makeObject(int obX,int obY,int obHeight,int obWidth){
rect(obX, obY, obHeight, obWidth);
}