有关变量的一些实例
我们已经学习了大量的变量理论,现在,我们将其中的一些用于实践。下面是三个以变量为中心的代码样本实例,请参阅解释代码的注释。
下例将播放头移动到当前时间轴上的某个随机帧: var randomFrame; // stores the randomly picked frame number var numFrames; // stores the total number of frames on the timeline numFrames = _totalframes; // assign _totalframes property to numframes
// pick a random frame randomFrame = Math.floor (Math.random () * numFrames +1);
gotoAndStop (randomFrame); // send playhead to choses random frame
下例计算两个电影剪辑之间的距离: var c; // a convenient reference to the circle clip object var s; // a convenient reference to the square clip object var deltaX; // the horizontal distance between c and s var deltaY; // the vertical distance between c and s var dist; // the total distance between c and s
c = _root.circle; // get reference to the circle clip s = _root.square; // get reference to the square clip deltaX = c._x - s._x; // compute the horizontal distance between the clips deltaY = c._y - s._y; // compute the vertical distance between the clips
// the distance is the root of (deltaX squared plus deltaY squared) dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// tidy references are much more readable than the alternative: // dist = Math.sqrt(((_root.circle._x - _root.square._x) * (_root.circle._x - _root.square._x)) // ((_root.circle._ y - _root.square._ y) * (_root.circle._ y - _root.square._ y)));
下例在华氏温度和摄氏温度之间转换: var fahrenheit; // temperature in Fahrenheit var celsius; // temperature in Celsius var convertDirection; // the system we are converting to legal values are "fahrenheit" and "celsius" fahrenheit = 451; // set a Fahrenheit temperature celsius = 20; // set a Celsius temperature convertDirection = "celsius"; // convert to Celsius in this case
if (convertDirection == "fahrenheit") { result = (celsius * 1.8) + 32; // calculate the Celsius value // display the result trace (celsius + " degrees Celsius is " + result + " degrees Fahrenheit."); } else if (convertDirection == "celsius") { result = (fahrenheit - 32) / 1.8; // calculate the Fahrenheit value // display the result trace (fahrenheit + " degrees Fahrenheit is " + result + " degrees Celsius."); } else { trace ("Invalid conversion direction."); }
alvin 的注释
上述第一个例子中,_totalframe是属性,Math.floor ()是方法。这些都可以在Flash的帮助文档中找到,恕不赘述。
第二和第三个例子实际上分别是完整的两个Flash电影中的代码段。如果你想要看源代码,请到moock先生的代码库去看看吧。
这些例子没有什么难以理解的地方,只是变量的实际应用。
出处:蓝色理想
责任编辑:无意
上一页 变量(9)- 局部变量 下一页 数据和数据类型(1) - 数据对信息
◎进入论坛Flash专栏版块参加讨论
|