夏的天

--我希望停留在夏天,但期望得越高,摔得总是太狠

 
 
 
 

自定义模块

 
 
模块内容加载中...
 
 
 
 
 
 
 
列表加载中...
 
 
 
 
 
 
 
 

优化

2009-6-12 12:30:32 阅读(13) 评论(0)

第一章  AS3的一些优化计算方法

  1. 用乘法来代替除法(当除数可转化为有限数的时候)。比如var n:Number = value * 0.5;要比var n:Number = value / 2;快。但差别并不是很大。只有在需要大量计算情况下,比如3D引擎中差别才比较明显。
  2. 用位运算代替除2或乘2。比如10>>1要比10*2快,而10<<1要比10*2快。从测试来看位运算几乎比乘除快一倍,但是一般情况下,我们不能选择位运算,比如我们就不能用13>>1来代替13/2,尽管前者比后者运算速度更快,但2者的运算结果却不一样。所以还是要看具体情况。
  3. 用unit()或int()代替取整运算Math.floor()和Math.ceil()。比如var test:uint = uint(1.5);要比var test:Number = Math.floor(1.5);快;而var test:uint = uint(1.5)+1;要比var test:Number = Math.ceil(1.5);也快。如果是Math.floor(),还可以用位运算(>>0)来代替。比如var test:uint =1.5>>0,比unit()或int()更快。
  4. 用乘-1来代替Math.abs()方法。比如var nn:Number = -23;var test:Number= nn < 0 ? nn * -1 : nn;要比var nn:Number = -23;var test:Number = Math.abs(nn);快。当然还有更多的优化计算的方法。一般来说,低级运算要比高级运算速度;内部方法比调用其他方法速度快。另外要注意的是,这些方法有的时候可能并一定适用。

第二章  Actionscript 优化指南

原著 Marco Lapi,alias Lapo, aw译

在这篇文章中,我们将讨论多种优化 Actionscript 代码的方法.此外我们也针对一些典型的游戏代码进行了系列测试,来最大限度的发掘、提高Flash播放器的性能。何时进行优化对现有程序进行优化的过程,有时十分的冗长与困难,这与原始代码的非优化程度有关,所以在投入大量时间进行代码优化之前,最重要的是要估计出要在什么地方对代码做出修改或替换。

一个游戏代码的最重要的部分就是主循环体,通常情况下该循环体要在flash的每一帧上执行,并控制游戏中的角色属性和重要的数据参数。而对于主循环体以外的部分,也可能是次要循环部分,同样要注意是给其否分配了过多的资源,而没有分配给那些更需要资源的核心部分。
通过积累在各处节约出来的时间(可能每处仅仅是几个毫秒),您会明显发现自己的swf运行得更加稳定,并且游戏感也大大加强。

简洁与高效的代码

书写出十分简洁、可以再次调用的代码(有时可能是面向对象的)是一项精细的工作,但这需要多年的编程经验。对于OOP(object oriented programming,面向对象的程序设计),有些场合根本利用不到它的优势,这使得它显得十分奢侈。在有限的资源条件下(可能是flash播放器的原因),通过更先进的方法,像刚刚提到的OOP,就可能反而导致令人不满意的结果。

我们并不是说OOP对游戏编程不好,只是在某些场合它显得过于奢侈和多余。毕竟有时候“传统的方法”却能得到更好的结果。大体而言,用OOP是比较好的,因为它让代码维护更加简单。但在后文中,你会看到有时为了充分发挥flashplayer性能,而不采用OOP技术。例如:处理快速滚动或者计算十分复杂的数学问题。基本的优化一提及代码优化,我们马上会联想到执行速度的改进,而很少去考虑系统资源的分配。这是因为当今,即使是将被淘汰的计算机,都有足够的内存来运行我们大部分的flash游戏(128M的内存足以满足大多数情况的需要,况且,512M的内存是当今新电脑的基本配置)

变量

在各种重要的代码优化手段中,有这么一条:在定义局部变量的时候,一定要用关键字var来定义,因为在Flash播放器中,局部变量的运行速度更快,而且在他们的作用域外是不耗占系统资源的。

aw附:var变量仅仅在花括号对中才有“生命”,个人认为没有系统学过编程的人容易出错的一个地方:

awMC.onLoad = function(){
  var aw = 1;
}
awMC.onEnterFrame = function(){
//不存在aw这个变量
}
一段非优化代码:
function doSomething()
{
mx = 100
my = 100
ar = new Array()

for (y=0; y < my; y++)
{
  for (x=0; x < mx; x++)
  {
   i = (y * mx) + x
   arr[i] = i  
  }
}
return arr
}

这段代码中,并未声明函数体内的那些变量(那些仅仅在函数内使用的变量)为局部变量,这使得这些变量被播放器调用的速度更慢,并且在函数执行完毕的时候仍然耗占系统资源。

下面列出的是经过改进的同样功能的代码:

function doSomething()
{
var mx = 100
var my = 100
var ar = new Array()

for (var y=0; y < my; y++)
{
  for (var x=0; x < mx; x++)
  {
   var i = (y * mx) + x
   arr[i] = i
  }
}
return arr
}

这样一来所有的变量均被定义为了局部变量,他们能够更快地被播放器调用。这一点在函数大量(10,000次)循环运行时显得尤为重要!当一个函数调用结束的时候,相应的局部变量都会被销毁,并且释放出他们占有的系统资源。


onEnterFrame 事件

onEnterFrame事件对于游戏开发者而言是非常有用的,它使得我们能够快速、反复地按照预设帧频(fps)运行一段程序。回想在Flash5的时代,这(onEnterFrame实时监控)是一种非常流行的技术,用这样的事件来控制机器游戏对手的逻辑,又或者我们可以在每一个子弹上设置这样的事件来监测子弹的碰撞。

实际上,我们并不推荐给过多的MoveClip添加这样的事件,因为这样做会导致“无头绪码(spaghetti code)”的出现,并且容易导致程序效率明显降低。

大多数情况下,用单独一个onEnterFrame事件就可以解决问题了:用这一个主循环来执行你所需要的操作。

另一个简单的办法是设置一个合适的帧频:要知道帧频越高,CPU资源就越紧张。在帧频为25-35(fps)之间时,onEnterFrame足以很好地执行较复杂代码,哪怕你的计算机配置较低。因此,在没有特殊要求的场合,我们不推荐使用高于60(fps)的帧频。

矢量图与位图

在处理图形前,我们一定要做出正确的选择。Flash能对矢量图和位图进行完美的兼容,然而矢量图和位图在播放器中的表现实质却完全不同。在用到矢量图的时候,我们要尽可能简化它们的形状,去除多余的端点。这样做将大大降低播放器用于呈现矢量图所要进行的计算量。另一个重要方面在于线条的运用,尽量减少和避免冗陈的线条结构,因为它们会直接影响到flash的播放效率。

当某个实例透明度小于100时,也会对播放速率造成影响,所以如果你发现自己的Flash播放速率过慢,就去挑出这些透明的实例来吧!

那么,如果真的需要呈现比较复杂的场景时,你就最好考虑使用位图实现。虽然Flash在对位图的渲染效率上并不是最优越的(比如和Flash的“兄长”Director比起来),但丰富的视觉内容呈现只能靠位图(与位图同复杂度的矢量图形渲染速率非常低)了,这也是很多基于区块的游戏中广泛采用像素图作为背景的原因。顺便要提到的是,Flash虽然对GIF,JPG和PNG都有所支持,但是渲染速度上PNG还是占有绝对优势,所

以我们建议flash中的位图都尽可能采用PNG格式。

影片剪辑(MovieClip)的可视性[下面将MovieClip简称为mc]

您可能会经常碰到这样一种情况:有大量不可见/屏幕外的mc等待出场(比如游戏中屏幕外的地图、人物等等)。
要知道,播放器仍然要消耗一定的资源来处理这些不可见/屏幕外的mc,哪怕他们是单帧,非播放的状态。

最好的解决办法之一是给这些mc一个空白帧,当他们不出现在屏幕上时,你能用gotoAndStop()语句跳转到这一帧,从而减少播放器对资源的需求。

请务必记住,这种情况下,简单的设置可见度属性为不可见( _visible = false )是无效的,播放器将继续按照这些mc所停留或播放的帧的复杂度来分配资源。

数组

数组在各种需要记录数据的应用程序和游戏中都被广泛的使用。

一个典型的例子就是基于区块的Flash游戏,在这样一类的游戏中,地图有时被存放成形如arr[y][x]的二维数组。虽然这是一种很常见的方法,但是如果用一维数组的话,却能提高程序的运行效率。另一个重要的方法来提高数组效率是在数组遍历的时候使用for in 循环来代替传统的 for 或者while循环语法。

例如:

一段代码如下


{
if (arr[i] > 50)
{
  // 进行某些操作
}
}

它的执行速度明显高于这一段代码:


{
if (arr[i] > 50)
{
  // 进行某些操作
}
}

前者的效率比后者提高了30%,这个数字在你的游戏要逐帧执行这一段代码的时候显得更加宝贵!




 

高级优化

1) for循环 和 while循环
用while循环将会得到比for循环更好的效率。然而,从数组中读取数据,用for in循环式最好的选择!

所以我们不推荐使用:


{
//进行某些操作
}而推荐使用
var i=-1
while (++i < 1000)
{
//进行某些操作
}

2) 从数组中读取数据
我们通过测试发现,for in循环的效率大大高于其他的循环方式。参看:

MAX = 5000
//数组赋值
for (i=0; i < MAX; i++)
{
arr[i] = i
}
var item = null
// For 循环
for (var i=0; i < MAX; i++)
{
item = arr[i]
}
// For 循环
for (var i in arr)
{
item = arr[i]
}
// While 循环
i = -1
while(++i < MAX)
{
item = arr[i]
}

3) 向数组中写入数据(while , for)可以看到while循环稍占优势。

4) _global(全局)变量同Timeline(时间轴)变量
我们猜测采用全局变量能提高变量调用速度,然而效果并不像预计的那样明显。

5) 单行、多行变量赋值
我们发现单行变量赋值效率大大高于多行。比如:

b = 0
c = 0
d = 100
e = 100

效率就不如:

d = e = 100

6) 变量名寻址
这个测试反映了变量名的预寻址是非常重要的,尤其是在循环的时候,一定要先给丁一个指向。这样大大节约了寻址时间。

比如:

t = getTimer()
for (var i=0; i < MAX; i++)
{
num = Math.floor(MAX) - Math.ceil(MAX)
}
t1.text = "Always lookup: " + (getTimer() - t)

就不如:

var floor = Math.floor
var ceil  = Math.ceil
for (var i=0; i < MAX; i++)
{
num = floor(MAX) - ceil(MAX)
}




 

7) 短变量名和长变量名
变量名越短,效率越高。考虑到长变量名也有它的好处(比如,便于维护等),因此建议在关键部位(比如大量循环出现的时候)使用短变量名,最好就1-2个字符。

8) 循环前、后声明变量
在测试前,我们认为循环前声明变量会更加节约时间,不料测试结果并不明显,甚至还恰恰相反!


t = getTimer()
for (var i=0; i < MAX; i++)
{
var test1 = i
}
t1.text = "Inside:" + (getTimer() - t)
// 外部声明
t = getTimer()
var test2
for (var i=0; i < MAX; i++)
{
test2 = i
}

9) 使用嵌套的if结构
当用到复杂的条件表达式时。把他们打散成为嵌套的独立判断结构是最佳方案。下面的代码我们进行了测试,发现这种效果改进明显!

a = 1
b = 2
c = -3
d = 4
var i=MAX
while(--i > -1)
{
if (a == 1 && b == 2 && c == 3 && d == 4)
{
  var k = d * c * b * a
}
}
//下面的判断更加节省时间
var i=MAX
while(--i > -1)
{
if (a == 1)
{
  if (b == 2)
  {
   if (c == 3)
   {
    if (d == 4)
    {
     var k = d * c * b * a
    }
   }
  }
}
}

10) 寻找局部变量(this方法同with方法比较)
局部变量的定位方法很多。我们发现用with比用this更加有优势!

obj.a = 1
obj.b = 2
obj.c = 3
obj.d = 4
obj.e = 5
obj.f = 6
obj.g = 7
obj.h = 8
obj.test1 = useThis
obj.test2 = useWith
MAX = 10000
function useThis()
{
var i = MAX
while(--i > -1)
{
  this.a = 1
  this.b = 2
  this.c = 3
  this.d = 4
  this.e = 5
  this.f = 6
  this.g = 7
  this.h = 8
}
}
function useWith()
{
var i = MAX
while(--i > -1)
{
  with(this)
  {
   a = 1
   b = 2
   c = 3
   d = 4
   e = 5
   f = 6
   g = 7
   h = 8
  }
}
}

11) 循环监听键盘事件
同刚才所提到的寻址一样,我们实现给一个指向会得到更好的效率,比如:

keyDown = Key.isDown
keyLeft = Key.LEFT

//我们再用 if (keyDown(keyLeft))
附:我们测试了按键代码和键值常量的效率发现并无太大差别。

12) Math.floor()方法与int()
这个问题曾在Flashkit的论坛被提出讨论过。测试表明,旧的int方法反而效率更高。我们的测试结果也反映了这一点。

13)eval表达式与中括号语法
我们并没有发现明显的差别,并不像刚才所述那样,旧的eval表达式比起中括号方法并没有太大的优势
var mc = eval("_root.myMc" + i)
var mc = _root["myMc" + i]
//两者效率差不多16) 涉及MC的循环:ASBroadcaster 同欢同循环的差别

结论

我们从这些测试结果中发现,对于不同的需求,采用不同的代码,我们可以大大提高脚本的执行效率。虽然我们在这里罗列了许多的优化代码的方法,需要大家自己测试、实验的还有很多(考虑到每个人的需求不同).如果你想更加深入地讨论这类问题。可以来我们的论坛。

aw附:
终于翻译完了,自己也学到很多好东西,大家又什么问题可以去gotoAndPlay的官方,也可以来我的Blog提出!

第三章  黑羽AS心得:浅释ActionScript的代码优化

本机函数要比用户定义的函数运行速度更快。本机函数即Flash中内有的一些函数(intrinsic),比如hitTest(),你没必要自己写一个类似的。

3.不要过多使用 Object 类型。
数据类型注释应力求精确,这样可以提高性能。只有在没有适当的备选数据类型时,才使用 Object 类型。同时也便于代码管理,时刻知道对象的类型和作用。同时也有利于编译器编译时优化。

4.避免使用 eval() 函数或数据访问运算符。
通常,较为可取且更有效的做法是只设置一次局部引用。不得已时才用eval,比如转换_droptarget为MovieClip时。

5.在开始循环前将 Array.length 赋予变量,尤其是大的循环。
在开始循环前将 Array.length 赋予变量(比如var iLength:Number),将其作为条件使用,而不是使用myArr.length 本身。
原因,在循环中,iLength是Number变量,会被放入寄存器使用,效率远比访问Array再得到length高。例如,应使用

var arrayLen:Number = fontArr.length;
for (var i:Number = 0; i < arrayLen; i++) {
    trace(fontArr[i]);
}

来代替:

for (var i:Number = 0; i < fontArr.length; i++) {
    trace(fontArr[i]);
}

6.注重优化循环及所有重复动作。
Flash Player 花费许多时间来处理循环(如使用 setInterval() 函数的循环)。

7.在局部变量够用时,不要使用全局变量。类静态变量也要少用。
全局变量是开发者的恶梦。实在需要全局变量的话,我建议使用singleton设计模式来进行管理。

8.声明变量时,添加 var 关键字。
这是为了编译时让编译器知道你的变量类型,优化编译。

黑羽补充一点:对关键字的使用要谨慎。
不赞成使用关键字作为自己的method和属性名,除非你确认后续开发不会用到相同的事件名和属性名。
但你怎么知道flash使用了多少隐藏关键字?太多了!比如说 className, invalidate, refresh, mouseOver等等不常用的关键词。好的方法是使用SEPY编辑器来写代码,那里面加亮了所有公布的和没有公布的关键词。而且因为很有可能和start,load,等这些常用的事件名重复,带来代码不必要的修改和麻烦。

9.对涉及到调用绘图资源的函数时,尽量先多判断再调用。
所有渐变,位置变化,创建删除MC,组件等函数都涉及到绘图资源的调用。在很多情况下,尽量先用逻辑判断变量或者对象的属性,必要时再调用这些函数。这样可以节省较多的计算资源。



 

阅读(13) | 评论(0) | 阅读全文>>

关于090320事件的检查

2009-3-20 15:35:32 阅读(38) 评论(0)

          因为自己一个很自私 很欠缺成熟的考虑 一个仓促的决定    让所有关心我的朋友操了很多的心 甚至让朋友的家人也跟着着急, 很大程度伤害了朋友的感情。  这里给所有关心我为我操心的人说一声对不起,尤其是我的几个兄弟:老白 夹子 耳朵 xiyuj ;感谢你们,你们对我很重要,请务必原谅我。 也请所有因为这件事情为我操心的朋友原谅我。
          我真的是没有把大家当外人,说话做事都第一时间跟大家说,不管事情有没有决定就跟大家商量,因为这个让大家跟着着急,又因为自己性格上的不成熟,让大家一次又一次的被我“晃点”,表示深深的歉意。我的做法确实很自私,没有顾及到大家的感受,请大家原谅我的不成熟,请大家再给我个机会。 再次恳求大家原谅我,我不能没有你们。

         ps: 这里由衷感谢 家属小梨 苹果 还有咱妈  让你们费心了! 真的很感激你们!

阅读(38) | 评论(0) | 阅读全文>>

还是PPT

2009-1-4 13:38:26 阅读(54) 评论(0)

还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

 还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

还是PPT - 夏天的画家 - 夏的天

阅读(54) | 评论(0) | 阅读全文>>

SONY ppt模版

2009-1-4 11:51:53 阅读(97) 评论(0)

SONY ppt模版 - 夏天的画家 - 夏的天

阅读(97) | 评论(0) | 阅读全文>>

公司介绍ppt

2009-1-4 11:49:25 阅读(86) 评论(0)

公司介绍ppt - 夏天的画家 - 夏的天

公司介绍ppt - 夏天的画家 - 夏的天

公司介绍ppt - 夏天的画家 - 夏的天

公司介绍ppt - 夏天的画家 - 夏的天

公司介绍ppt - 夏天的画家 - 夏的天

公司介绍ppt - 夏天的画家 - 夏的天

阅读(86) | 评论(0) | 阅读全文>>

几个最近做的ppt模版

2009-1-4 11:33:55 阅读(53) 评论(0)

Intel

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

NBA

几个最近做的ppt模版 - 夏天的画家 - 夏的天

高露洁

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

佳洁士

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

几个最近做的ppt模版 - 夏天的画家 - 夏的天

阅读(53) | 评论(0) | 阅读全文>>

Biotherm 代言人

2008-12-20 16:49:29 阅读(65) 评论(0)

    今天跟老婆去影棚拍片(碧欧泉新的代言人) 自己也偷练了一下Biotherm 代言人 - 夏天的画家 - 夏的天       不可用作商业用途!请不要转贴

以后我还要多加这方面的锻炼啊。。。

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

 

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

Biotherm 代言人 - 夏天的画家 - 夏的天

阅读(65) | 评论(0) | 阅读全文>>

Textures

2008-10-16 13:04:40 阅读(183) 评论(0)

Textures (WireFrame, Bitmap, MovieAsset, Video, etc.) PaperVision3D

Author photo
 
Reminder: Papervision3D is still in 2.0 alpha. Before testing these samples, please make sure to update to the latest version of the Papervision3D 2.0 alpha Great White branch.

Materials
Why do you need to learn about materials in Papervision3D? Take a sphere for example: How do you determine whether the sphere is a globe, an eye, or a basketball? You only know by which material is mapped to the sphere.

This article will cover the basics of the materials available through Papervision3D and teach you how to add materials to Planes. Let's get started, we’ve got a lot of “material” to cover:

Materials Base Class
Before we dive into every material available, it's important to note that every material extends an abstract base class called “MaterialObject3D” (org.papervision3d.core.proto.MaterialObject3D). This means you'll find the following properties in every material:

Very Common Usage among All Materials
1. name (String): the name of the material
2. interactive (Boolean): allows listeners to be assigned. Interactivity will be covered in an upcoming article.
3. oneSide or doubleSided (Boolean): maps the material to the front AND back of the mesh. For instance, a spinning Plane will show the same material on both sides of the Plane.
4. smooth (Boolean): applies a smoothing algorithm to the material. Turning this on for many materials or high-resolution materials has an impact on performance.

Less Common, but Useful Usage
5. bitmap (BitmapData): gives you access to the bitmap data of the material.
6. tiled (Boolean): determines whether the texture is tiled across the material. On primitive objects, you’ll have to adjust the maxU and maxV for this to take effect. For more information on UV mapping visit: http://en.wikipedia.org/wiki/UV_mapping 
7. maxU (Number): holds the max number of “U” in the UV map.
8. maxV (Number): holds the max number of “V” in the UV map.
9. scene (Scene3D): a reference to the scene where the object belongs.

Special Situation Usage
10. invisible (Boolean): indicates whether the mesh faces are drawn.
11. opposite (Boolean): indicates whether the face is flipped. Only use this if the material is double sided.
12. widthOffset (Number): holds the original width of the bitmap before auto mip-mapping resizes
13. heightOffset (Number): holds the original height of the bitmap before auto mip-mapping resizes

Wireframe Material (or Composite Material including Wireframe Material)
14. lineColor (Number): holds an RGB value (e.g., 0xabc123) of the faces’ outline.
15. lineAlpha (Number): holds a number between 0 and 1 representing the percentage of transparency for the line.
16. lineThickness (Number): determines the thicknesss of the line.

Color Material Only (or Composite Material including Wireframe Material)
1. fillColor (Number): holds an RGB value (e.g., 0xabc123) of the fill of the mesh.
2. fillAlpha (Number): holds a number between 0 and 1 representing the percentage of transparency for the fill.

1. Wireframe
We used Wireframe materials in Part 1 to show that our 3d objects were truly 3d. The Wireframe material outlines the triangles used to create the entire object.

WireframeMaterial.JPG

WireframeMaterial( color:Number=0xFF00FF, alpha:Number=100, thickness:Number = 0 )

2. Color Color materials project a solid color on to the 3d object. I've mainly seen color materials used in demos as they don’t allow for much customization.

ColorMaterial.JPG

ColorMaterial( color:Number=0xFF00FF, alpha:Number = 1, interactive:Boolean = false )

3. Bitmap If you want to use an image on your 3d object, you’ll need to use one of the following methods to get the bitmap data of your .gif, .jpeg, or .png onto the object.

Commons.png

The bitmap used in the demos is the Wikimedia commons logo above. Bitmap Material, Bitmap Asset Material, and Bitmap File Material are three different ways of doing the same thing so they will all yield the following result:

BitmapMaterial.JPG

a. Bitmap
The Bitmap Material allows you to take any BitmapData and attach it to the material. The most typical usage is embedding a bitmap then grabbing the bitmapData from the bitmap to pass into the material. You can find information on embedding bitmaps in Flex here:
http://livedocs.adobe.com/flex/3/html/help.html?content=embed_3.html
BitmapMaterial( asset:BitmapData=null, precise:Boolean = false)

b. Asset (Flash CS3 only)
Bitmap Asset Materials are used to map a bitmap in your Flash library to an object. Just add any bitmap to your library, right-click -> properties

BitmapAssetMaterial( linkageID:String, precise:Boolean = false )
c. Color
The Bitmap Color Material works practically the same as the Color Material above, but this bitmap version allows you access to the bitmapData to draw or change pixels of the color to your liking.
BitmapColorMaterial(color:Number=0xFF00FF, alpha:Number=1)

d. File
Bitmap File Materials simply take a string that points the location of the image. You can also add listeners to the material if you need to check on progress or when the bitmap finishes loading.
BitmapFileMaterial( url :String="" )

e. Viewport
BitmapViewportMaterial.JPG

A Bitmap Viewport Material takes a bitmap snapshot of a viewport and allows you to project that snapshot onto another 3d object. Think of it like being at a basketball game and watching the game on the jumbotron instead of looking directly at the game.
BitmapViewportMaterial(bitmapViewport:BitmapViewport3D, precise:Boolean=false); BitmapViewport3D(viewportWidth:Number=640, viewportHeight:Number=480, autoScaleToStage:Boolean = false, bitmapTransparent:Boolean=false, bgColor:int=0x000000, interactive:Boolean=false, autoCulling:Boolean=true);

f. Wireframe
The Bitmap Wireframe Material is similar to the standard Wireframe Material, but it allows for access to the bitmapData of the material.

BitmapWireframeMaterial(color:Number=0xFF00FF, alpha:Number=1,thickness:Number=3)

4. MovieClip
Papervision3D allows you to take your MovieClip directly from your Flash library and attach them your 3d objects using the linkage identifier. For Flex, you embed the published .swfs and MovieClip as you normally would. The following image demonstrates an attached MovieClip in the middle of an animation of a shape tween:

MovieMaterial.jpg

a. Asset (Flash CS3 Only)
MovieAssetMaterial( linkageID:String="", transparent:Boolean=false, animated:Boolean=false, createUnique:Boolean=false, precise:Boolean = false)
b. MovieMaterial
MovieMaterial( movieAsset:DisplayObject=null, transparent:Boolean=false, animated:Boolean=false, precise:Boolean = false )

5. Video Stream
Yes, you can play videos on 3d objects. Yes, it looks really cool.

VideoStreamMaterial.JPG

VideoStreamMaterial ( video:Video, stream:NetStream , precise:Boolean = false )

6. Shade
Since Shaded Materials are all based on a light pointing at a material and reflecting (or not-reflecting) the light, you’ve probably guessed that you need to create a light first:

light = new PointLight3D();

You can position this light wherever you want using its x, y, and z properties then the shaded objects will appear to look at the light. If you want the light to be visible, you need to add pass in a parameter of “true” then “addChild” it to the scene. Although, you’ll probably find yourself leaving the light invisible and creating a 3d object at the same location that appears to be the light source like a sun, lamp, or sunlamp.

This “light” will become the first parameter of each shaded material. Only one light is currently supported in Papervision3D, but there are plans to allow multiple lights in the distant future.

The best way to see how all of these materials work is to test them out with the included reference sheet at the end of the article.

a. Cell
http://en.wikipedia.org/wiki/Cel-shaded_animation
The Cell Material uses two colors and an amount of steps you want to take to blend the two.

CellMaterial.JPG

CellMaterial(light:LightObject3D, color_1:int, color_2:int, steps:int)

b. Environment Map
http://en.wikipedia.org/wiki/Environment_map
An environment map is receiving a bitmap being projected from the light. More advanced environment maps require “shaders” which will be covered in a later article.

EnvMapMaterial.JPG

EnvMapMaterial(light:LightObject3D, lightMap:BitmapData, backEnvMap:BitmapData=null, ambientColor:int = 0)

c. Flat Shade
http://en.wikipedia.org/wiki/Flat_shading
Flat shading gives one solid shade of light to each polygon. This effect is much more noticeable on spheres than plane and cubes to you can see the light curve around the sphere.

FlatShadeMaterial.JPG

FlatShadeMaterial(light:LightObject3D, diffuse:uint=0xffffff, ambient:uint=0x000000)

d. Gouraud
http://en.wikipedia.org/wiki/Gouraud_shading
Gouraud Materials allow for smoother shading. Limitations are discussed in the link above.

GouraudMaterial.JPG

GouraudMaterial(light3D:LightObject3D, lightColor:int = 0xFFFFFF, ambientColor:int=0x000000)

e. Phong
http://en.wikipedia.org/wiki/Phong_shading
Phong Materials are similar to Gouraud Materials, but they also allow for specular highlights.

PhongMaterial.JPG

PhongMaterial(light3D:LightObject3D, lightColor:int, ambientColor:int, specular:int)

7.Composite
A composite material is simply multiple materials mashed together to form one material. Here we see a bitmap material put together with a wireframe material.

CompositeMaterial.JPG

8. Run-Time Material Swapping
Swapping material at run-time is simple as can be (thanks to a recent update by Ralph):

my3DObject.material = myMaterial;

The most obvious use is for rollovers, but interactivity with Papervision3D is being saved for a later article.

9. Examples of Materials around the Web
*Note: Some of these examples use Papervision3D’s shaders (which I will cover in a later article) and may not be working off the latest Papervision3D repository.

http://www.zeropointnine.com/blog/a-papervision-20-alpha-example
http://www.unitzeroone.com/blog/2008/03/12/papervision3d-shaders-bumpmap-example-sourcecode-for-cs3/

10. Reference Sheets
This article includes reference sheets for all the materials covered here so you can test all of the properties yourself within Flash and Flex. The Flash sheet covers the two asset materials that are Flash-specific while the Flex sheet covers all of the other materials in an ActionScript project.

阅读(183) | 评论(0) | 阅读全文>>

2008年10月16日

2008-10-16 12:54:18 阅读(97) 评论(0)

Papervision3D Movement- Going Where No MovieClip Has Gone Before

Author photo
 
Changing Position- Move that 3D Thing! 

If you’re anything like me, you remember how excited you were years ago when you first wrote a simple line of code, ball._x++, in an onEnterFrame event and gleefully watched a ball fly across the stage. I promise you that little moving ball ain’t got nothin’ on what you’re about to learn here.

Properties: x, y, and z 

You position an object in 3d space by plotting out its x, y, and z coordinates. Now it only makes sense, just like that ball moving across the stage years ago, that incrementing an x, y, or z value in Papervision3D using an ENTER_FRAME event will achieve the same purpose. Yet, there are a few gotchas:

  • x:0, y:0, and z:0 is the center of the stage(unlike a traditional flash stage with x:0 and y:0 in the upper-left corner)
  • y++ moves up
  • z++ moves forward

Every DisplayObject3D uses these x, y, and z properties and you can access them directly on the object:

myCube.x++; //moves myCube right one pixel

You don’t typically directly increment the position values of a 3d object as there are methods and Tweening engines that simplify movement in 3d space

Click to Demo
Click on Preview Above to Run Demo.

Methods: moveForward(), moveBackward(), moveLeft(), moveRight(), moveUp(), andmoveDown() I’ll give you one guess to figure out what “moveForward()” does to a 3d object. Give up? “moveForward()” moves the 3d object forward. Unlike a z++, moveForward() takes rotation into account. This means your object will move forward no matter what direction it faces. Let’s imagine two diametric examples to make sure we’re clear:

  • Going down can be moving forward: Imagine an airplane in a nose-dive. Even though you could say the plane is going down, the rotation of the plane has changed in such a manner that the pilot would say, “We are moving forward towards the ground.”
  • Going forward can be moving down: Imagine a motorcycle popping a perfect wheelie. The motorcycle would be pointed toward the sky, but you would have to define his motion as “moveDown()” because it’s turned so far back on its back wheel that the bottom is moving forward.

So it all boils down to this: if you want to move a sphere named “sphere” 10 pixels forward:

sphere.moveForward(10);// moves a sphere forward 10 pixels

If you want the sphere to continue to move forward, place the preceding line of code within an ENTER_FRAME event handler.

Adjusting Scale- Because Bigger is Always Better

Properties: scale, scaleX, scaleY, and scaleZ

There’s one underlying rule in life that we all have to deal with on a daily basis: size matters.

In 3d space, the only way to visually determine the size of an object is to compare it to another nearby object. If you’re new to manipulating 3d space, you’ll run into this problem often because you have to take the size of your 3d object and all of the camera properties into account.

If you need to adjust the size of the object compared to other objects and you like where the object is positioned, the easiest method is to play with its scale settings.

  • scaleX - stretches/shrinks the object along the X-axis or left and right
  • scaleY- stretches/shrinks the object along the Y-axis or up and down
  • scaleZ - stretches/shrinks the object along the Z-axis or front and back
  • scale - strecthes/shrinks the object equally on all axes (that’s plural for more than one axis)

The following example demonstrates scaling in 3D:

Click to Demo
Click on Preview Above to Run Demo.

Simple Rotations*- You Spin Me Right Round, Baby, Right Round

*author’s note: This section is subject to change in future revisions based on current internal discussions within the Papervision3D team

Properties: rotationX, rotationY, rotationZ, localRotationX, localRotationY, andlocalRotationZ

Methods: pitch(), yaw(), and roll() In Flash, whenever you rotate a MovieClip it only rolls right or left, similar to the hands turning on a clock. Papervision3D adds two new ways to rotate. The one you’re familiar with, turning clockwise or counter-clockwise, is known as rolling, or rotationZ because the object is rotating around the Z-axis. You can think of the Z-axis as you and friend facing each other holding long axle with a wheel at the middle. Turning the axle in your hands would make the wheel roll. So the axle is the Z-axis and turning an object on the Z-axis makes it roll.

Yaw (rotationY) and pitch (rotationX) might be new to you, but the concepts are just as simple. For instance, the earth spins on its Y-axis as do figure skaters, tornadoes, and those toy tops you used to play with as a kid. If you need to hold a Y-axis to grasp the concept, just grab your nearest spindle of burnable CDs and start spinning your CDs around it. That plastic rod jotting up out of the base is a good example of a Y-axis and the CD spinning around the Y-axis an example of yaw or rotationY. Simple, right?

Last, but not least, is the pitch or rotationX. Get up out of your chair and do a somersault. Assuming you were successful, you’ve completed a 360 degree pitch because you rotated around the X-axis. If you just got in trouble by your boss for doing somersaults in the office, just tell him you’re doing research and do another one.

Now that you understand the concept, let’s talk about how and why to use each variation:

rotationX, rotationY, and rotationZ

Consider these three properties as “object axis rotation”. Most commonly you set the rotation once then forget about it. Think of a space shuttle. The space shuttle, while in Earth’s atmosphere, flies like any other airplane: horizontally. Yet, when it’s time to lift off into outer space, the space shuttle flies vertically. In this situation, you would adjust the rotationX 90 degrees and then forget about it. So consider these rotations as a way to orient your object to the direction you’d like it to face.

localRotationX (pitch), localRotationY (yaw), localRotationZ(roll)

These local rotations will now rotate around the object axis. So once you orient your object with the base rotations, you can now rotate around the new orientation with the local rotations. (Take note that the method pitch(), yaw(), and roll() achieve the exact same functionality as these local rotation properties. They take a degrees parameter and will update the local rotation by that many degrees). A local rotation also does the following things which you’ll need to remember:

  1. 1. Updates incrementally. Each local rotation builds upon the prior local rotation. Although this is correct, you will most likely not get the results you expect. Adding 3D rotations is much more complicated than you may initially assume.
  2. 2. Modifies the orientation rotation. This may seem counter-intuitive, but must be done to maintain proper moveForward(), moveRight(), etc. functionality.

Lastly, setting a rotationX after setting a localRotationX will reset all of the local rotations. This means the object will return to the orientation rotation defined in rotationX, rotationY, and rotationZ. This, in effect, cancels out the changes made to the orientation by the local rotations.

The following example demonstrates the points made above. The sliders adjust the orient rotations while the buttons do a 360 rotation around a local rotation. The demo pretty clearly shows the difficulty in combining multiple rotations at the same time:

Click to Demo
Click on Preview Above to Run Demo.

Controlled Rotations- lookAt()

Methods: lookAt()

You probably gathered from the “Simple Rotations” section that combining 3D rotations can get complicated quite quickly. If you want to delve into the math behind 3D rotations and solutions you can use to control them mathematically, read up on the following topics:

On the other hand, if you’re looking for a simpler solution, read on.

The lookAt() method is available on every DisplayObject3D (sphere, plane, cube, etc.). It allows you take make one object look at another. The syntax is very simple:

plane.lookAt(sphere); //results in the plane looking at the sphere

Now you may be thinking, “I see what this does, but how does it help control rotations?” The answer is that you can now position dummy objects around the scene using x,y, and z and then lookAt() those objects to create the desired rotation of the main object. If you want to rotate something to the upper left, place an object up and to the left then look at it. The following example demonstrates an arrow looking at different spheres:

Click to Demo
Click on Preview Above to Run Demo.

If you don’t want the object you’re looking at to be seen, don’t add it to the scene.

Orbiting with Pivot Points

Pivot Points allow you to group a whole bunch of 3d object together at different positions and rotate them around one axis. It’s similar to how all the planets in the solar system rotate around the Sun. The basic usage of a Pivot Point is very simple, yet it can yield pretty cool results. Create a couple objects, create a Pivot Point (just a basic DisplayObject3D), add the objects to the Pivot Point, then add the Pivot Point to the scene:

var sphere1:Sphere = new Sphere(); var sphere2:Sphere = new Sphere(); var pivotPoint:DisplayObject3D = new DisplayObject3D(); //add your objects to the pivot point pivotPoint.addChild(sphere1); pivotPoint.addChild(sphere2); //add your pivot point to the scene scene.addChild(pivotPoint);

After this is all said and done, you can rotate the Pivot Point using the methods discussed above and the objects you placed within the Pivot Point will all rotate together. Check out the following example to get the idea:

Click to Demo
Click on Preview Above to Run Demo.

Tweening in 3D with TweenMax

There are many open source options for making things move in Flash. I’ve decided to use an engine called TweenMax because it’s a solid, fast engine that’s easy to learn in an online article. Follow this link and click the big green “Download Now” button toward the top of the page:

http://blog.greensock.com/tweenmaxas3/

Extract the .zip to wherever you keep your classes and set a class path to import TweenMax. A typical syntax is short sweet and simple (yet has limitless options):

TweenMax.to(myObject, duration, {myProperty:endResult});

You can play around with the tween customizer on the TweenMax homepage to generate some more examples. Make sure and check out the easing methods from the code generator to smooth out your transitions. After playing with the code generator, try swapping in any 3d object and 3d property into the static to() method:

TweenMax.to(sphere, 2, {z:1000});//Tweens a sphere from its current z location to z 1000

Go ahead and try out each property we’ve looked at. You can even try tweening multiple properties simultaneously. You’ll quickly see how easy it is. Let’s combine some of the ideas we’ve learned for the final demo.

Click to Demo
Click on Preview Above to Run Demo.

The preceding example can be thought of like this:

  1. 1. Tween a dummy object to the x, y, and z of a sphere
  2. 2. Update the arrow object to lookAt() the dummy object for proper rotation
  3. 3. Update the arrow object’s x, y, and z to follow the dummy object through 3d space

The nifty little curving effect comes from an option called “bezierThrough” provided by TweenMax. The syntax looks like this:

TweenMax.to(dummyArrow, 2, {x:sphere.x, y:sphere.y, z:sphere.z, bezierThrough:[{x:1000, y:1000}], onUpdate:updateArrow, ease:Quart.easeInOut});//Tweens a dummy object to a sphere with a bezier of x:1000 and y:1000. Also calls updateArrow() each time the tween updates

The updateArrow function should look something like this:

private function updateArrow():void { //gives a little lag between the arrow for smoother rotating dummyArrow.moveBackward(200); //arrow looks at dummy arrow arrow.lookAt(dummyArrow); // arrow copies the x, y, and z of the dummyArrow arrow.copyPosition(dummyArrow); }

There are truly limitless possibilities of movement in 3D. If the movement happens around you in everyday life, you can bet there’s some way to achieve that same movement effect in Papervision3D. So let your imagination run wild and make cool stuff!

阅读(97) | 评论(0) | 阅读全文>>

查看所有日志>>

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2010