我如何使用我现在拥有的对象的代码,我可以存储球反弹的次数和颜色(当我添加随机颜色时)和速度。任何指针或提示都会很棒。我是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;
}
}
}
答案 0 :(得分: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);
答案 1 :(得分:0)
请注意,在Proccesing中,您不需要为此创建新文件,代码可以在同一个文件中(非常糟糕的做法,如下所示)或IDE的新选项卡中。如果您使用的是Processing IDE,您可以从右侧的箭头菜单中选择“new tab”,它将为您创建文件。它将具有“.pde”扩展名。