0

如何将我现在拥有的代码与一个对象一起使用,我可以在其中存储球反弹的次数和颜色(当我添加随机颜色时)和速度。任何指示或提示都会非常有用。我是 OOP 的新手,它会让我感到困惑。提前致谢

  float x;
  float y;
  float yspeed = 0;
  float xspeed = 0;
  float balldiameter = 10;
  float ballradius = balldiameter/2;

  void setup() {
  size (400,400);
  background (255);
  fill (0);
  ellipseMode(CENTER);
  smooth();
  noStroke();
  x = random(400);
  y = 0;
  }

  void draw() {
  mouseChecks();
  boundaryChecks();
  ballFunctions();
  keyFunctions();
  }

  void mouseChecks() {
    if (mousePressed == true) {
    x = mouseX;
    y = mouseY;
    yspeed = mouseY - pmouseY;
    xspeed = mouseX - pmouseX;
    }
  }

  void boundaryChecks() {
    if (y >= height - ballradius) {
      y = height - ballradius;
      yspeed = -yspeed/1.15;
    }
    if (y <= ballradius) {
      y = ballradius;
      yspeed = -yspeed/1.35;
    }
    if (x >= width -ballradius) {
      x = width -ballradius;
      xspeed = -xspeed/1.10;
    }
    if (x <= ballradius) {
      x = ballradius;
      xspeed = -xspeed/1.10;
     }
   }

   void ballFunctions() {
   if (balldiameter < 2) {
     balldiameter = 2;
     }
   if (balldiameter > 400) {
     balldiameter = 400;
     }
   ballradius = balldiameter/2;
   background(255); //should this be in here?
   ellipse (x,y,balldiameter,balldiameter);
   yspeed = yspeed += 1.63;
    // xspeed = xspeed+=1.63;
   y = y + yspeed;
   x = x + xspeed; 
   }
  void keyFunctions() {
    if (keyPressed) {
      if(keyCode == UP) {
      balldiameter +=1;
    }
    if (keyCode == DOWN) {
      balldiameter -=1;
      }
    }
   }
4

2 回答 2

1

您可能需要执行以下操作:
创建一个名为Ball.pde
在该文件中写入的新文件:

public class Ball {
    public float x;
    public float y;
    public float yspeed;
    public float xspeed;
    public float diameter;
    public float radius;  

    public Ball(float initial_x, float initial_y, float diam) {
        this.x = initial_x;
        this.y = initial_y;
        this.xspeed = 0;
        this.yspeed = 0;
        this.diameter = diam;
        this.radius = diam/2;
    }

    public void move() {
       // movement stuff here
    }
}

这会给你一个非常基础的Ball课程。你现在可以在你的主草图文件中使用这个类,如下所示:

Ball my_ball = new Ball(50, 50, 10);

您可以使用以下方式访问球成员:

my_ball.xspeed;
my_ball.yspeed;
my_ball.anything_you_defined_in_ball;

这将允许您将球的所有相关变量存储在其自己的类中。你甚至可以创建超过 1 个。

Ball my_ball1 = new Ball(50, 50, 10);
Ball my_ball2 = new Ball(20, 20, 5);
于 2012-11-07T05:01:25.637 回答
0

请注意,在 Proccesing 中您不需要为此创建新文件,代码可以在同一个文件中(非常糟糕的做法,如下所述)或在 IDE 的新选项卡中。如果您使用的是 Processing IDE,您可以从右侧的箭头菜单中选择“新选项卡”,它将为您创建文件。它将具有“.pde”扩展名。

于 2012-11-07T16:18:36.653 回答