首先,draw() 是一个循环,默认情况下,每秒调用 60 次。所以检查keyPressed 或mousePressed 内部抽签有点不精确。自己看:
诠释我;无效绘制(){如果(keyPressed)i++; println(i);}
只要你按下一个键,每次按下它就会增加一个以上的i,更糟糕的是,每次都会增加不同的数量。
所以你最好改用回调函数keyPressed()
int i; void draw(){println(i);} void keyPressed(){i++;}
另一件事是,我认为逻辑有点奇怪。您增加 i 的方式的原因...
// i = 0
if (keyPressed)
if (key == 'q')
{
// you add a turret at index 0
turret[i] = new Place(1157, 405); // Hitting 'q' on the keyboard causes a Null Pointer exception that points to this line
// here ideally i = 1
i++;
g=1;
}
if(g==1)
{
// here you call circle and keyPressed on an empty slot in the array
// turret [1] have no instance... hence the NPE
turret[i].circle();
turret[i].keyPressed();
}
}
然后i 永远不会重置,因此它会不断超出您的数组长度...
对于在运行时动态修改的列表,我更喜欢使用列表,比如 ArrayList。但是你也可以用一个数组来做到这一点。然后,您必须检查并将“迭代器”限制为数组中的已占用插槽。
这是我认为您正在寻找使用 ArrayList 的内容:
类中的键处理可能与 keyPressed 相同:
ArrayList<Place> turret = new ArrayList<Place>();
void setup()
{
size(1501, 811);
background(255);
}
void draw()
{
//if the list is not empty
if (turret.size() > 0) {
//it could be a regular for loop also
for (Place p : turret) {
p.circle();
p.keyHandle();
}
}
}
void keyPressed(){
// you can add as much Places as you want :)
if(key == 'q'){
turret.add(new Place(int(random(width)), int(random(height))));
}
}
class Place
{
int xPos, yPos;
Place(int x, int y)
{
xPos = x;
yPos = y;
}
void circle()
{
ellipse(xPos, yPos, 30, 30);
}
void move(int amount, char xy)
{
frameRate(10);
pushMatrix();
translate(xPos, yPos);
if (xy == 'x')
xPos+=amount;
if (xy == 'y')
yPos+=amount;
circle();
popMatrix();
}
int v=0;
// you don't want to override processing keyPressed
// unles you register it, so I'm changing the name
void keyHandle()
{
if (keyPressed)
{
if (key == 'd' && v==0)
move(30, 'x');
if (key == 'a' && v==0)
move(-30, 'x');
if (key == 's' && v==0)
move(30, 'y');
if (key == 'w' && v==0)
move(-30, 'y');
if (key == 'x' && v==0)
{
v=1;
fill(0);
}
}
}
}
我真的会选择 ArrayList,但这里有一个与数组相同的例子。
PImage grid;
Place[] turret;
int nextInsert = 0;
void setup()
{
size(1501, 811);
background(255);
//grid = loadImage("Grid.png");
turret = new Place[10];
}
void draw()
{
for(int i =0 ; i < turret.length; i++){
if(turret[i] != null){
turret[i].circle();
turret[i].keyHandle();
}
}
}
void keyPressed(){
if(key == 'q'){
if(nextInsert < turret.length){
turret[nextInsert] = new Place(int(random(width)), int(random(height)));
nextInsert++;
}
}
}
class Place
{
int xPos, yPos;
Place(int x, int y)
{
xPos = x;
yPos = y;
}
void circle()
{
ellipse(xPos, yPos, 30, 30);
}
void move(int amount, char xy)
{
frameRate(10);
pushMatrix();
translate(xPos, yPos);
if (xy == 'x')
xPos+=amount;
if (xy == 'y')
yPos+=amount;
circle();
popMatrix();
}
int v=0;
void keyHandle()
{
if (keyPressed)
{
if (key == 'd' && v==0)
move(30, 'x');
if (key == 'a' && v==0)
move(-30, 'x');
if (key == 's' && v==0)
move(30, 'y');
if (key == 'w' && v==0)
move(-30, 'y');
if (key == 'x' && v==0)
{
v=1;
fill(0);
}
}
}
}