即使我停止按键,keyPressed()事件仍会触发

时间:2019-03-21 00:20:54

标签: java processing

因此,我绘制的对象将根据我按下的箭头键开始向上或向下移动,但是一旦放开,它将继续朝相同方向移动,除非我按下随机键。如果我按它,它开始向上移动,甚至在松开后仍继续向上移动。如果我再按下它,它就会开始向下移动,即使我不再按下它,它也会继续向下移动。如果在移动过程中按下了除向上箭头键或向下箭头键以外的任何键,它将停止移动。

主要草图:

Defender defender1;
PImage background;
int x=0; //global variable background location

void setup() {
    size(800,400);
    background = loadImage("spaceBackground.jpg");
    background.resize(width,height);
    defender1 = new Defender(200,200);
}

void draw () {
    image(background, x, 0); //draw background twice adjacent
    image(background, x+background.width, 0);
    x -=4;
    if(x == -background.width)
        x=0; //wrap background
    defender1.render();
    defender1.keyPressed();
}

后卫阶级​​:

class Defender {
    int x;
    int y;

    Defender(int x, int y) {
        this.x = x;
        this.y = y;
    }

    void render() {
        fill(255,0,0);
        rect(x,y,50,20);
        triangle(x+50,y,x+50,y+20,x+60,y+10);
        fill(0,0,100);
        rect(x,y-10,20,10);
    }

    void keyPressed() {
        if (key == CODED) {
            if (keyCode == UP) {
                defender1.y = y-1;
            } else if (keyCode == DOWN) {
                defender1.y = y+1;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

每次调用defender1.keyPressed()时,您就在调用draw()函数。

keykeyCode变量保留最近按下的键,而不管当前是否按住该键。

要检查当前是否正在按下任何键,可以使用keyPressed变量。

或者您可以将代码更改为仅从草图级别的defender1.keyPressed()函数调用keyPressed()

您可以在the reference中找到更多信息。

无耻的自我推广:here是有关处理中用户输入的教程。