# 24、《每周一点canvas动画》——森林与星海

#### 一、重力

    。。。
function move(ball){
ball.vy += gravity;   //重力加速度

ball.xpos += ball.vx;
ball.ypos += ball.vy;
ball.zpos += ball.vz;

if (ball.ypos > floor) {  //触地反弹
ball.ypos = floor;
ball.vy *= bounce;
}
if(ball.zpos > -fl){   //3维场景设置
var scale = fl/(fl + ball.zpos);
ball.scaleX = ball.scaleY = scale;
ball.x = vpX + ball.xpos * scale;
ball.y = vpY + ball.ypos * scale;
ball.visible = true;
}else{
ball.visible = false;
}
}
。。。

#### 二、屏幕环绕

##### 1. hello！树先生

1. tree.js ——简单树
2. binaryTree.js ——二叉树
3. natureTree.js ——自然树

1.简单树

2.二叉树

/* gen: 树枝的节点代数，默认是6个节点*/
/* angle: 每次在节点树枝的旋转角度*/
/* branchLength: 树枝的长度*/

function Tree(color, angle, genNum, branchLength){
this.x = 0;
this.y = 0;
this.xpos = 0;
this.ypos = 0;
this.zpos = 0
this.scaleX = 0.85;
this.scaleY = 0.85;
this.gen = 0;
this.alpha = 1;
this.color = utils.parseColor(color);
this.angle = (angle === undefined) ? 0.3 : angle;
this.genNum = (genNum === undefined) ? 6 : genNum;
this.branchLength = (branchLength === undefined) ? 40 : branchLength;

}

Tree.prototype.draw = function(ctx){
ctx.save()
ctx.translate(this.x, this.y);
this.branch(ctx, 0);           //初始角度为0， 绘制树干
ctx.restore();
}

Tree.prototype.branch= function(ctx, initAngle){
this.gen++;
ctx.save();
ctx.strokeStyle = this.color;
ctx.rotate(initAngle);
ctx.scale(this.scaleX, this.scaleY);

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.translate(0, -this.branchLength);
ctx.lineTo(0, 0);
ctx.stroke();

if(this.gen <= this.genNum){       //判断当前的节点代数是否大于设置的节点数
this.branch(ctx, this.angle);   //画右边树枝
this.branch(ctx, -this.angle);  //画左侧树枝
}
ctx.restore();

this.gen--;
}

3.自然树

2.无限森林

...
function move (tree) {
tree.xpos += vx;
tree.ypos += vy;
tree.zpos += vz;

if(tree.ypos < floor){  //让树的Y轴坐标落在设置好的地面上
tree.ypos = floor;
}

if (tree.zpos < -fl) {  //如果z坐标超出了屏幕回到一个老远的位置
tree.zpos += 10000;
}
if (tree.zpos > 10000 - fl) {  //如果z轴的坐标超过了我们设置的距离，
让它回到一个近的位置
tree.zpos -= 10000;
}
//3维环境设置
var scale = fl / (fl + tree.zpos);
tree.scaleX = tree.scaleY = scale;
tree.x = vpX + tree.xpos * scale;
tree.y = vpY + tree.ypos * scale;
tree.alpha = scale;
}
...

3.星海

...
...