声明:本教程参考代码本色学习做的笔记,但也会有很多自己个人的体会与经验分享。只要有高中基础并且至少学习过一门编程语言即可学习本教程。这里给出一个processing函数查询网站
java的物理世界-01入门案
一.安装
首先是环境的搭建,点击官网下载,该网站需要翻墙,考虑到可能你不会翻墙(我也不可能教你),于是我将Windows64的版本上传到了网盘
链接:https://pan.baidu.com/s/1oqR54J1fUvbfg1HTr8Wupw
提取码:6nuo
请看这里安装教程
二.案例
1.游走
class Walker{
int x,y;
Walker(){
//width and height are the width and height of the window you create
x=width/4;
y=height/4;
}
void display(){
//set color of point
stroke(150);
point(x,y);
}
void step(){
int choice = (int)random(4);
if(choice==0){
x++;
}else if(choice ==1){
x--;
}else if(choice==2){
y++;
}else{
y--;
}
}
}
//Now We hava finished the class Walker,the next work is for Sketch--setup() and draw()
Walker walker;
void setup(){
size(500,600);
walker = new Walker();
//set color of background of the window
background(0);
}
void draw(){
walker.step();
walker.display();
}
程序从setup函数开始,一般放的是初始化的代码,接下来循环执行draw函数
2.随机函数测试
void setup(){
size(600,600);
background(0);
}
int counts[] = new int[10];
void draw(){
int index = (int)random(10);
counts[index]++;
int w = width/10;
fill(255);
//开始循环绘制
for(int i=0;i<10;i++)
{
rect(i*w,0,w,counts[i]);
}
}
3.90%朝鼠标方向移动
class Walker{
int x = width/2;
int y = height/2;
//该函数的作用是让点朝着(x,y)的方向移动
void step(int x,int y){
if((x-this.x)!=0){
float gradient = (float)(y-this.y)/(x-this.x);
stroke(150);
this.x+=1;
this.y+=gradient;
point(this.x,this.y);
}
else{
stepRandom();
}
}
void stepRandom(){
int choice = (int)random(4);
if(choice==0){
x++;
}else if(choice ==1){
x--;
}else if(choice==2){
y++;
}else{
y--;
}
stroke(150);
point(x,y);
}
}
//walker对象的创建应该写在setup里面否者此时的
//width和height还是默认值100,100
Walker walker;
void setup(){
size(600,600);
background(0);
walker = new Walker();
}
void draw(){
int x = mouseX;
int y = mouseY;
int result = (int)random(10);
if(result<=8){
walker.step(x,y);
}else{
walker.stepRandom();
}
}
最后的突变是由于此时斜率太大了。