【问题标题】:Manipulating non-static variables操作非静态变量
【发布时间】:2022-01-14 10:55:59
【问题描述】:

所以在我的课堂上,我们让对象根据 x 和 y 坐标变量移动,这很简单。但是,如果我在单独的静态类中声明 x 和 y 变量,我似乎只能让我的工作,而教师示例代码似乎没有这样做。我一直在看老师的示例代码,它为什么会这样工作是有道理的,但是当我尝试将类似的方法应用于我的代码时,它似乎不起作用,我无法找出我的'我做错了。

教师代码:

// A Bug that moves from left to right and vibrates up and down randomly in the output window 
class Bug {
    // The x- and y-coordinates as well as the speed a Bug is moving
    int x;
    int y;
    int speed;
    // The color of the Bug
    int red;
    int green;
    int blue;

    // Initialize the x- and y-coordinates, the speed and the RGB colors
    Bug() {
        x = -80;
        y = (int) random(10, height - 10);
        speed = (int) random(1, 5);
        red = (int) random(255);
        green = (int) random(255);
        blue = (int) random(255);
    }

    // Set the fill color and ellipseMode
    // Create a for loop that draw “bugs” as six consecutive attached circles 
    void displayBug() {
        fill(red, green, blue, 175);
        ellipseMode(CENTER);
        for (int ctr = 0; ctr < 90; ctr += 15) {
            circle(x + ctr, y, 20);
        }
    }

    // Add the speed instance variable to the x-coordinate
    // Add a random value between -2 and 2 to the y-coordinate
    void moveBug() {
        x += speed;
        y += (int) random(-2, 2);
    }

    // Constrain the y-coordinate between 10 and the height of the output window minus 10
    void boundaries() {
        y = constrain(y, 10, height - 10);
    }
    // If the x-coordinate is greater than width of the output window, reset the x-coordinate to 
    -80

    void resetBug() {
        if (x > width) {
            x = -80;
        }
    }
}

我尝试在没有静态类的情况下移动圆圈的示例:

class Test{
    int x;
    int y;
    int speed;
    Test(){
        x = 1;
        y =(int) random(0,400);
        speed = 1;
    }
    void drawThing(){
        circle(x,y,10);
    }
    void moveThing(){
        x += speed;
    }
}

【问题讨论】:

  • 那应该怎么读?
  • 我们可以看看你是如何在你的代码中使用这个类的吗?正如它所写的那样,它应该从左到右移动......如果你正确使用你的方法。

标签: java class processing


【解决方案1】:

这是我的驱动程序中的代码:

Test draw;
Test move;
void setup(){
size(400,400);
draw = new Test();
move = new Test();
}
void draw(){
draw.drawThing();
move.moveThing();
}

但是用draw.moveThingmove 换成move.moveThing 已修复。

【讨论】:

  • 只是一个建议,但您可以在绘制之前更新位置(移动)。这样,用户看到的内容和您正在计算的内容将保持一致。当然,在 60 FPS 时这并不重要,但在某些极端情况下它可能会有所帮助,特别是如果您可以“暂停”移动。顺便说一句,感谢您发布这个自我回答,很少有新用户这样做,我们永远不知道它将来会帮助谁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
相关资源
最近更新 更多