• UID1571
  • 登录2018-08-17
  • 粉丝6
  • 发帖145
  • 科研点数0点
优异服役勋章
耕耘者十字勋章
zt07elecfreaks 发布于2018-01-16 16:41
0/267

Interesting Processing Programming Guidance for Designer10-Class and Object

楼层直达
What is class? What is object?



Class is a concept that only exists in object programming. You can't think over it as too deep and profound. Actually for lots of cases in the previous chapters, you have already used class unconsciously but not dive deeper into it.

Then what's the hell of class and object?

Simply speaking, class is used to describe the property and characteristics of something. It is abstract. Object is an entity of class. It is figurative.

Take an example. Suppose "country" is a class, then "China" is the object of this class. If "insect" is a class, then "butterfly" is the object of this class.

When defining a class, we will package something. In the program, it can be either variables or functions. Instantiating the class, the object generated will include these characteristics. Classes are designed to be modular, to be lazy, and to be more efficient. If you don't want to do repeat work, you can try to use class more often.

Now, I believe you must have a basic conception for class. Let's look at a real case in the below.



Grammar of Class:

class name{

Member Variables

Constructor Function

Member Functions

}



First of all, you have to write the key word class at the beginning.

Then name the class. Generally, the first letter of the class must be capitalized so that it can differentiate other data types. Like the String type mentioned before, actually it is a class that has already defined in the program. So unlike basic data types like int, float, boolean, the first letter is capitalized. Except for this point, it has same naming regulation with common variable name and function name. You must try to make it more concise and easier for understanding and do not duplicate existing function names and variable names.


Write a brace behind. What within the brace is the common part of class.

Member Variables: Variables in the class. Be used to store data.

Constructor Function: Initialize object.

Member Functions: Functions for realizing special effects in the class.

Of course, these are not necessary inside the class. According to different requirements, we can have different ways of writing. In the following, let's start from the simplest to explore it step by step and build a "class block".



Build Class Block



Class block is an empty shell that does not contain anything. In the Processing, it is allowed to write like this.

Code Example (12-1):



[cceN_cpp theme="dawn"]
MyClass mc;

void setup(){
mc = new MyClass();
}
void draw(){
}
class MyClass{
}
[/cceN_cpp]



Code Explain:

Function class, setup and draw are "sibling". It can write before function setup as well as behind function draw. However, the general way of writing is to write below function draw.

The first line of code declares a class object named mc. This format of writing is same with declaration of data types like int, float.

The new statement in function setup initializes the object mc. You cannot ignore this step. Only through initialization, can the object be put to use. With this method, we have built an empty shell related to class. Except to write class under function draw, we can write it on the new tag. This can be better managed when your file scale grows larger and larger.  The method is to click a downward triangle mark in the right side of file name tag and choose "build a new tag".






Input tag name, then it is completed.(Tag name may not be consistent with the name of class.)






After that, you can write class into it.




The tags built will be stored into the same class catalogue under engineering documents in pdf format. When running the program, it will load these files into a project automatically.




Class Application - Build Information Library for People or Goods



Next, we start to make a small test with this powerful class. We will begin to use member variables in the class to solve some practical problems. In the last chapter, we have used three different types of arrays to store people's information.



[cceN_cpp theme="dawn"]
String[] name;

boolean[] gender;
float[] heights;
int[] age;
void setup() {
name = new String[]{"Mike", "Jake", "Kate"};
gender = new boolean[]{true, true, false};
heights = new float[]{0.98, 1.34, 1.7};
age = new int[]{5, 10, 18};
}
[/cceN_cpp]



Picture below indicates the packing status of data, which stores information separately based on the unit of array.






Although this can achieve the purpose of storage, obviously it is not intuitive. As for attributes like name, gender, height, age and so on, it is finally attached to an individual. It will be much more intuitive if we regard "person" as a unit. But because the program itself does not provide this composite data type to indicate "person", so, at this moment, class can be put to use. We can use new method to organize these data. After reorganization, it is a bit like the following picture showed.






Person will be regard as a class to pack these data.

Here's an example showing you how to realize "Person".

Code Example (12-2):



[cceN_cpp theme="dawn"]
Person mike;

void setup(){
mike = new Person();
mike.age = 10;
mike.gender = false;
mike.heights = 1.8;
println(mike.age);
}
class Person{
boolean gender;
float heights;
int age;
}
[/cceN_cpp]



Code Explain:

Same with common variable, member variables in a class are used as containers only. Once built, you can read or write.

In order not to duplicate the name of the default variable height, the floating point variable use "heights " instead of " height ".

Through class name "." + variable name , we are able to visit members in the class.

Object name is based on person's name. But in order to invoke information more conveniently, we remain a String type inside the class to store names.



Class Application - Particle System



Create "Particles" - Use Member Variables



Since we have familiar with the usage of member variable, we can enter into a more interesting part--use class to write particle system. Particle system is a concept with no specific definition. It can be used to describe particles' status and movements such as rain and snow, river, dust and smoke, waterfall, flame, etc.. Birds flying in the sky, fishes swimming in the water, bullets in a shooting game as well as explosion can be simulated with it.

Certainly, in a broad sense, any image can actually be regarded as particles. Like images displayed on digital screens, they are consisted of a bunch of particles (pixels). They have fixed positions, hues, and sizes. In the following, let's use class first to simulate some basic properties of particles.

Code Example(12-3):



[cceN_cpp theme="dawn"]
void setup() {

size(700, 700);
p = new Particle();
p.col = color(202, 31, 201);
p.x = 350;
p.y = 350;
p.r = 200;
}
void draw() {
background(33, 48, 64);
fill(p.col);
ellipse(p.x, p.y, p.r * 2, p.r * 2);
}
class Particle {
color col;
float x, y;
float r;
}
[/cceN_cpp]








Code Explain:

Seeing from the result, it only draws a circle on the certain place of the screen with a specified color. But the data structure has changed already. This is a simplified particle system. In the class, we have created four member variables to represent the particles' horizontal coordinate, vertical coordinate, size and color.



Create "Particles" - Use Constructor Function



Next, let's do some extension for the conception of class. Add constructor functions in to particle class.

The usage of constructor function is to initialize some variable values. We can write some variables, which require to set parameters beforehand, into constructor function.

Code Example (12-4):



[cceN_cpp theme="dawn"]
Particle p;

void setup() {
size(700, 700);
p = new Particle();
}
void draw() {
background(33, 48, 64);
fill(p.col);
noStroke();
ellipse(p.x, p.y, p.r, p.r);
}
class Particle {
color col;
float x, y;
float r;
Particle() {
col = int(random(0, 255));
x = random(width);
y = random(height);
r = random(100, 500);
}
}
[/cceN_cpp]








Code Explain:

The format of constructor is add parenthesis, brace behind class name. This is very close to the writing method of common definition functions except no void written before it.

In setup, the function of " new " is to initialize objects. Once we have used this command, constructor function will execute automatically. Thus, every time we open the program, we will get a different result. Suppose we hope to invoke constructor functions for multiple times, we can use "new". Add the following code to event KeyPressed, then you can reset particle parameters through keys.



Code Example:





[cceN_cpp theme="dawn"]
void keyPressed() {

p = new Particle();
}
[/cceN_cpp]



Create "Particle" - Import Parameter to Constructor Function



Constructor is a function after all. So it also allows the importation of multiple parameters.

Code Example(12-5):





[cceN_cpp theme="dawn"]
Particle p;

void setup() {
size(700, 700);
p = new Particle(350, 350, 400, color(255, 200, 0));
}
void draw() {
background(33, 48, 64);
fill(p.col);
noStroke();
ellipse(p.x, p.y, p.r, p.r);
}
class Particle {
color col;
float x, y;
float r;
Particle(float x_, float y_, float r_, color col_) {
x = x_;
y = y_;
r = r_;
col = col_;
}
}
[/cceN_cpp]






Code Explain:

Parameters within parenthesis of constructor function are called formal parameter. It is not a real exist variable but works as a transmission only. Adding underline behind the formal parameter name has no special meaning. It only plays a role of alphabet character. This is a comparatively common way of writing, which convenient you to correspond to the value assigned.

When using new to initialize objects, the quantity and type of parameters filled in must be consistent with constructor function, or it will go wrong.

Besides, constructor function also supports overlapping. You can define multiple constructor functions and invoke them according to the quantity and type of the parameters in constructor function.

Code Example:



[cceN_cpp theme="dawn"]
class Particle {

color col;
float x, y;
float r;
Particle() {
col = int(random(0, 255));
x = random(width);
y = random(height);
r = random(100, 500);
}
Particle(float x_, float y_, float r_, color col_) {
x = x_;
y = y_;
r = r_;
col = col_;
}
}
[/cceN_cpp]




Create "Particles" - Use Member Function



In the last, I am going to introduce Member Function to you. Member Function by name means functions included in the class. We can visit it externally through object name "." function name .

Code Example(12-6):





[cceN_cpp theme="dawn"]
Particle p;

void setup() {
size(700, 700);
p = new Particle(350, 350, 400, color(255, 200, 0));
}
void draw() {
background(33, 48, 64);
p.randomMove();
fill(p.col);
noStroke();
ellipse(p.x, p.y, p.r, p.r);
}
class Particle {
color col;
float x, y;
float r;
Particle(float x_, float y_, float r_, color col_) {
x = x_;
y = y_;
r = r_;
col = col_;
}
void randomMove() {
x+= random(-10, 10);
y+= random(-10, 10);
}
}
[/cceN_cpp]





Comprehensive Class Application - Particle System (Array)



Use Array

In the former, we have introduced member variable, constructor function, member function. We have made a single particle obtain property and movement status. Next, we will use array to build a group of particles and create a particle system which can move along with mouse.

Code Example (12-7):



[cceN_cpp theme="dawn"]
Particle[] circles;

void setup(){
size(700,700);
circles = new Particle[300];
for(int i = 0;i < circles.length;i++){
circles = new Particle(random(width),random(height));
}
}
void draw(){
background(244,213,63);
noStroke();
for(int i = 0;i < circles.length;i++){
circles.randomMove();
circles.follow();
circles.draw();
}
}
class Particle{
float x,y;
int colorStyle;
float ratio;
float r;
Particle(float x_,float y_){
x = x_;
y = y_;
r = random(5,20);
colorStyle = int(random(4));
ratio = random(0.005,0.05);
}
void randomMove(){
x = x + random(-5,5);
y = y + random(-5,5);
}
void follow(){
x = x + (mouseX - x) * ratio;
y = y + (mouseY - y) * ratio;
}
void draw(){
float alpha = 255;
if(colorStyle == 0){
// red
fill(232,8,80,alpha);
}else if(colorStyle == 1){
// purple
fill(104,8,240,alpha);
}else if(colorStyle == 2){
// black
fill(0,alpha);
}else if(colorStyle == 3){
// white
fill(255,alpha);
}
ellipse(x,y,r * 2,r * 2);
}
};
[/cceN_cpp]





Operate Effect:





Code Explain:

In addition to basic data types like int, float, class can also be arrayed.

Member function follow has realized follow effect with a typical expression "A = A + (B - A) * ratio". Among it, a stands for the coordinate of front point, B stands for the coordinate of target point, ratio for proportion when every time it closes to. In the example, A is for the current coordinate position of the particle, B is for the current coordinate position of the mouse. The calculation of "B-A" will get the distance between them. Multiply a parameter behind this distance, the result value is a fraction of this value. Therefore it becomes more and closer. Besides, because of the frame ratio defaulted in the program is very high, so the execution times for every second is quite much. Thus, if you want to see the obvious follow effect, you should set the value of ratio comparatively small.

Same with this section of code, we can try to delete some commands"//" (remarks), and watch the result to know the operation mechanism of program.

Delete function randomMove and follow at the same time. Particles will remain the initialization status and keep still.




Delete function randomMove and only remain function follow. Particles will not vibrate.



Delete function follow and only remain function randomMove. Particles vibrate in the same place.



Try to write background into setup and revise alpha value in function draw to be 50. It will become a special brush tool.







Different transparency will create different effect. Delete randomMove and only remain follow.







Comprehensive Class Application - Button



Except for realizing particle system, you can use class to make various controlling components like buttons, slide bars. Although lots of plug-in are ready for use, there are many advantages to write controls by yourself. One is you can get familiar with the usage of class, the other is you can customize needed functions more flexible. Of course, you can write button without class. But in you use multiple buttons in a program, it would be quite troublesome for not using class. You have to declare variables and functions repeatedly. While using class, it saves you lots of time with only one effort. It is equivalent to produce a mould. When needed, you can use it to produce components.

Code Example(12-8):



[cceN_cpp theme="dawn"]
Button btn;

void setup() {
size(700, 700);
btn = new Button(350, 600, 400, 40);
}
void draw() {
background(33, 48, 64);
btn.check();
btn.draw();
if (btn.active) {
for (int i = 0; i < 100; i++) {
noStroke();
fill(random(255), random(255), random(255),200);
float r = random(0, 400);
ellipse(350, 350, r, r);
}
} else {
fill(0);
ellipse(350, 350, 400, 400);
fill(50);
ellipse(350, 350, 360, 360);
}
}
void mousePressed() {
btn.mousePressed();
}
class Button {
float x, y, w, h; // separately represents the button center position's x coordniate, y coordinate, button length and height.
boolean over; // test if mouse on the button.
boolean active; // test if button is pressed.
Button(float x_, float y_, float w_, float h_) {
x = x_;
y = y_;
w = w_;
h = h_;
}
void check() {
if (mouseX > x - w/2 && mouseX < x + w/2 && mouseY > y - h/2 && mouseY < y + h/2) {
over = true;
} else {
over = false;
}
}
void mousePressed() {
if (over) {
active = !active;
}
}
void draw() {
if (over) {
fill(41, 238, 176);
} else {
fill(80);
}
rectMode(CENTER);
rect(x, y, w, h);
}
}
[/cceN_cpp]





Operate Effect:





Code Explain:

Function check is used to judge whether mouse is on the button. Because button is a rectangle, so you can calculate its borderlines.

Member variable active is used to record the activation status of button. When mouse is pressed upon the button, it will get negative active state so that to achieve shift effect.

Comprehensive Class Application - Slide Bar

Below is an example relative to slide bar.

Code Example (12-9):



[cceN_cpp theme="dawn"]
Bar b;

void setup() {
size(700, 700);
b = new Bar(350, 600, 400, 15);
}
void draw() {
background(33, 48, 64);
b.draw();
fill(random(255), random(255), random(255));
noStroke();
float l = 400 * b.ratio;
ellipse(350, 350, l, l);
}
void mousePressed() {
b.mousePressed();
}
void mouseDragged() {
b.mouseDragged();
}
void mouseReleased() {
b.mouseReleased();
}
class Bar {
boolean isDrag; // Judge if it is dragging.
boolean isActive; // Judeg if mouse is upon the control poin.
float startX, endX; // The x coordniate of slide bar's beginning point and terminal point.
float x, y; // slide bar's x,y coordinate.
float w, r; // The width of slide bar, radius of control point.
float circleX; // control point's x coordinate.
float ratio; // ratio
Bar(float x_, float y_, float w_, float r_) {
x = x_;
y = y_;
w = w_;
r = r_;
circleX = x;
startX = x - w/2;
endX = x + w/2;
}
void draw() {
if (isActive && isDrag) {
circleX = mouseX;
if (circleX > endX) {
circleX = endX;
} else if (circleX < startX) {
circleX = startX;
}
}
// calculate ratio.
ratio = (circleX - startX)/w;
// draw slide bar.
stroke(130);
strokeWeight(4);
line(startX, y, endX, y);
if (isActive) {
fill(41, 238, 176);
} else {
fill(130);
}
noStroke();
ellipse(circleX, y, r * 2, r * 2);
}
void mousePressed() {
if (dist(mouseX, mouseY, circleX, y) < r) {
isActive = true;
} else {
isActive = false;
}
}
void mouseDragged() {
isDrag = true;
}
void mouseReleased() {
isDrag = false;
isActive = false;
}
}
[/cceN_cpp]





Operate Effect:





Code Explain:

Because the button of slide bar is round, so we can judge whether mouse is upon the button using distance.

Variable ratio stands for the value proportion of slide bar. It is calculated according to the button's coordinate.



END



The above introduced knowledge points are just a corner of an iceberg. There are more important features and usages of class such as polymorphism, inheritance. When you find you are quite familiar with the above usages but it cannot satisfy your needs at the same time, then you can dive deeper to learn more senior conceptions. Technique, it is not better for the more your mastered, the deeper you dive into. Actually you only have to know the basic rules thoroughly, have good creative ideas, then you can also make artworks that funny enough.

As with your study becomes deeper and deeper, you will find class is everywhere. All kinds of plug-ins, libraries are made of class. We shall use it more consciously and learn to reuse and abstract.

You can also do lots of extension for the above particle system. For example, combining with Newtonian mechanics, add properties like force, speed and acceleration speed into class. It can simulate particle systems that is more natural, more close to physical movement regulations. Since this is not the key point of this series, I will not extend it in detail. If you have interest in it, you can refer to Daniel Shiffman's The Nature of Code. As for force, there has more detailed narration.



Some Cases Related to Particle System



Import force, increase more particles.





Import force, use picture to draw particles.






Use particle system in the three-dimensional system.





Next chapter will be our final chapter of the top half part of the whole series. Fundamental part is closing to the end. Let's enter into the world of 3D graphic drawing.


This article comes from designer Wenzy.
Relative Readings:


Interesting Programming Guidance for Designer——Processing Initial Touch
Interesting Programming Guidance for Designer–Create Your First Processing Program
Interesting Programming Guidance for Designer--Get Your Picture Running(Part One)
Interesting Programming Guidance for Designer--Get Your Picture Running(Part Two)
Interesting Programing Guidance for Designer–Program Process Control- Loop Statement
Interesting Programming Guidance for Designer--Program Process Control--Condition Statement (Part One)
Interesting Programming Guidance for Designer--Program Process Control--Condition Statement (Part Two)
Interesting Programming Guidance for Designer--Custom Functions and Fractal Recursion
Interesting Programming Guidance for Designer--Custom Functions and Fractal Recursion
Interesting Processing Programming Guidance for Designer--Color Control
Interesting Processing Program Guidance for Designer-Media Loading and Event
Interesting Processing Program Guidance for Designer- Data Storage Box



https://www.elecfreaks.com/11835.html
您需要登录后才可以回帖
发表回复

杩斿洖椤堕儴