2016-01-17 38 views
0

我在这里的代码是一个动画,它显示了一个按照我喜欢的方式移动的圆。我想有10个圆圈,我假设我使用循环或可能是一个数组,但我不太确定如何做到这一点。同时,我想让它首先动画不会移动,但在按下特定的按键时开始移动,而当按下同一个按键时停止。使用多个省略号和使用keyPressed控制的动画

color a = color(random(255), random(255), random(255), random(125, 250)); 
float dia = random(60, 80); 
float x; 
float y; 

float speedX = random(-3, 3); 
float speedY = random(-3, 3); 

void setup() { 
    background(255); 


size(400, 200); 
    x = random(dia/2, width-dia/2); 
    y = random(dia/2, height-dia/2); 

} 

void draw() { 
    background(255); 
    noStroke(); 
    fill(a); 
    ellipse(x, y, dia, dia); 
    x = x + speedX; 
    y = y + speedY; 
    if(speedX > 0 && x >= width - dia/2) { 
    speedX = speedX * -1; 
    } 
    if(speedX < 0 && x <= dia/2) { 
    speedX = speedX * -1; 
    } 
    if(speedY > 0 && y >= height - dia/2) { 
    speedY = speedY * -1; 
    } 
    if(speedY < 0 && y <= dia/2) { 
    speedY = speedY * -1; 
    } 
} 

回答

0

您可以通过封装你需要画一个圆为类的数据得到的多个圈。它可能是这个样子:

Circle c; 

void setup() { 
    size(400, 200); 
    c = new Circle(); 
} 

void draw() { 
    background(255); 
    c.draw(); 
} 

class Circle { 
    color a = color(random(255), random(255), random(255), random(125, 250)); 
    float dia = random(60, 80); 
    float x = random(dia/2, width-dia/2); 
    float y = random(dia/2, height-dia/2); 

    float speedX = random(-3, 3); 
    float speedY = random(-3, 3); 

    void draw() { 
    noStroke(); 
    fill(a); 
    ellipse(x, y, dia, dia); 
    x = x + speedX; 
    y = y + speedY; 
    if (speedX > 0 && x >= width - dia/2) { 
     speedX = speedX * -1; 
    } 
    if (speedX < 0 && x <= dia/2) { 
     speedX = speedX * -1; 
    } 
    if (speedY > 0 && y >= height - dia/2) { 
     speedY = speedY * -1; 
    } 
    if (speedY < 0 && y <= dia/2) { 
     speedY = speedY * -1; 
    } 
    } 
} 

然后获得多个圈子,你只是创建Circle类的多个实例,并将它们添加到ArrayList

ArrayList<Circle> circles = new ArrayList<Circle>(); 

void setup() { 
    size(400, 200); 
    for (int i = 0; i < 5; i++) { 
    circles.add(new Circle()); 
    } 
} 

void draw() { 
    background(255); 
    for (Circle c : circles) { 
    c.draw(); 
    } 
} 

对于用户互动,看看事件的方法,如mousePressed()keyPressed()The Processing reference应该是你的第一站。祝你好运。

+0

我接受了你的建议,但试过让圆圈显示为图像,然后当我按下空格键时让它们开始移动,但当按下它时,它只是一个静态图像,只有在按住空间时才会移动酒吧。不知道我在做什么错 试图把椭圆代码设置为所以它会作为你看到的第一个东西出来,但只有一个圆,然后我按空格键只有那个圆移动 With keyPressed ,我认为需要有一个else语句来说明停止并显示动画,但我不知道该怎么做 –