史上最简单的3D森林

// 一种简单的树类



package {

import flash.display.Sprite;

public class Tree extends Sprite {

   public var xpos:Number = 0;

public var ypos:Number = 0;

   public var zpos:Number = 0;

   public function Tree() {

init();

   }

   public function init():void {

graphics.lineStyle(0, 0x00ff00); // 树的颜色

graphics.lineTo(0, -140 - Math.random() * 20);   // 树干

graphics.moveTo(0, -30 - Math.random() * 30);

graphics.lineTo(Math.random() * 80 - 40, // 随机生成的树枝

-100 - Math.random() * 40);

graphics.moveTo(0, -60 - Math.random() * 40);

graphics.lineTo(Math.random() * 60 - 30,

-110 - Math.random() * 20);

   }

}

}
------------------------------------------------------------------------------
// 利用简单树组成的森林



package {

import flash.display.Sprite;

import flash.events.Event;

import flash.events.KeyboardEvent;

import flash.ui.Keyboard;

[SWF(backgroundColor=0x000000)];   // 设置背景为黑色,但不知为什么无效

public class Trees extends Sprite {

    private var trees:Array; // 存放所有的树

    private var numTrees:uint = 100;    // 定义100颗够了

    private var fl:Number = 250; // 屏幕距离眼睛一般设置为200--300

    private var vpX:Number = stage.stageWidth / 2; // 物体太小后消失点

    private var vpY:Number = stage.stageHeight / 2;

    private var floor:Number = 50; // 水平面高度

    private var vz:Number = 0; // Z轴透视深度速度

    private var friction:Number = 0.98; // 阻尼系数

    public function Trees() {

   init();

    }

    private function init():void {

   trees = new Array();

   for (var i:uint = 0; i < numTrees; i++) {

var tree:Tree = new Tree(); // 生成树

trees.push(tree);

tree.xpos = Math.random() * 2000 - 1000;

tree.ypos = floor;

tree.zpos = Math.random() * 10000;

addChild(tree); //

   }

   addEventListener(Event.ENTER_FRAME, onEnterFrame);

   stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);

    }

    private function onEnterFrame(event:Event):void {

   for (var i:uint = 0; i < numTrees; i++) {

var tree:Tree = trees;

move(tree);

   }

   vz *= friction; // 阻尼后的Z轴方向的速度

   sortZ(); // Z轴消隐

    }

    private function onKeyDown(event:KeyboardEvent):void {   // 加减速控制

   if (event.keyCode == Keyboard.UP) {

vz -= 1;

   } else if (event.keyCode == Keyboard.DOWN) {

vz += 1;

   }

    }



    private function move(tree:Tree):void {

   tree.zpos += vz; // 更新移动距离(速度)

   if (tree.zpos < -fl) { // 如果树走到眼睛后面,则移动到远处

tree.zpos += 10000;

   }

   if (tree.zpos > 10000 - fl) {   // 如果树太远,大于屏幕外1000则移回

tree.zpos -= 10000;

   }

   var scale:Number = fl / (fl + tree.zpos);   // 计算透视深度系数

   tree.scaleX = tree.scaleY = scale;

   tree.x = vpX + tree.xpos * scale;

   tree.y = vpY + tree.ypos * scale;

   tree.alpha =   scale * .7 + .3; // 不同距离用不同的alpha混色,显示大气透视(朦胧感)

    }

    private function sortZ():void {

   trees.sortOn("zpos", Array.DESCENDING | Array.NUMERIC);

   for (var i:uint = 0; i < numTrees; i++) {

var tree:Tree = trees;

setChildIndex(tree, i);

   }

    }

}

}
posted @ 2010-02-12 10:55  与时俱进  阅读(363)  评论(0编辑  收藏  举报
友情链接:同里老宅院民居客栈