DFdou's Blog Life is short,Be yourself.

406/101

AS3-Water ripples

这是国外某友人在08年弄的一个东西,今天刚好在reader里看到,分享下吧:http://www.derschmale.com/2008/08/03/water-ripples-revisited-as3-only-version/

Demo:

Rippler.as:

/*
Copyright (c) 2008 NascomASLib Contributors.  See:

http://code.google.com/p/nascomaslib

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package be.nascom.flash.graphics
{
    import flash.display.BitmapData;
    import flash.display.BitmapDataChannel;
    import flash.display.BlendMode;
    import flash.display.DisplayObject;
    import flash.events.Event;
    import flash.filters.ConvolutionFilter;
    import flash.filters.DisplacementMapFilter;
    import flash.geom.ColorTransform;
    import flash.geom.Matrix;
    import flash.geom.Point;
    import flash.geom.Rectangle;

    /**
     *
     * The Rippler class creates an effect of rippling water on a source DisplayObject.
     *
     * @example The following code takes a DisplayObject on the stage and adds a ripple to it, assuming source is a DisplayObject already on the stage.
     *
     *     <listing version="3.0">
     *         import be.nascom.flash.graphics.Rippler;
     *
     *         // create a Rippler instance to impact source, with a strength of 60 and a scale of 6.
     *         // The source can be any DisplayObject on the stage, such as a Bitmap or MovieClip object.
     *         var rippler : Rippler = new Rippler(source, 60, 6);
     *
     *         // create a ripple with size 20 and alpha 1 with origin on position (200, 50)
     *         rippler.drawRipple(100, 50, 20, 1);
     * </listing>
     *
     * @author David Lenaerts
     * @mail david.lenaerts@nascom.be
     *
      */
    public class Rippler
    {
        // The DisplayObject which the ripples will affect.
        private var _source : DisplayObject;

        // Two buffers on which the ripple displacement image will be created, and swapped.
        // Depending on the scale parameter, this will be smaller than the source
        private var _buffer1 : BitmapData;
        private var _buffer2 : BitmapData;

        // The final bitmapdata containing the upscaled ripple image, to match the source DisplayObject
        private var _defData : BitmapData;

        // Rectangle and Point objects created once and reused for performance
        private var _fullRect : Rectangle;             // A buffer-sized Rectangle used to apply filters to the buffer
        private var _drawRect : Rectangle;            // A Rectangle used when drawing a ripple
        private var _origin : Point = new Point();    // A Point object to (0, 0) used for the DisplacementMapFilter as well as for filters on the buffer

        // The DisplacementMapFilter applied to the source DisplayObject
        private var _filter : DisplacementMapFilter;
        // A filter causing the ripples to grow
        private var _expandFilter : ConvolutionFilter;

        // Creates a colour offset to 0x7f7f7f so there is no image offset due to the DisplacementMapFilter
        private var _colourTransform : ColorTransform;

        // Used to scale up the buffer to the final source DisplayObject's scale
        private var _matrix : Matrix;

        // We only need 1/scale, so we keep it here
        private var _scaleInv : Number;

        /**
         * Creates a Rippler instance.
         *
         * @param source The DisplayObject which the ripples will affect.
         * @param strength The strength of the ripple displacements.
         * @param scale The size of the ripples. In reality, the scale defines the size of the ripple displacement map (map.width = source.width/scale). Higher values are therefor also potentially faster.
         *
         */
        public function Rippler(source : DisplayObject, strength : Number, scale : Number = 2)
        {
            var correctedScaleX : Number;
            var correctedScaleY : Number;

            _source = source;
            _scaleInv = 1/scale;

            // create the (downscaled) buffers and final (upscaled) image data, sizes depend on scale
            _buffer1 = new BitmapData(source.width*_scaleInv, source.height*_scaleInv, false, 0x000000);
            _buffer2 = new BitmapData(_buffer1.width, _buffer1.height, false, 0x000000);
            _defData = new BitmapData(source.width, source.height, false, 0x7f7f7f);

            // Recalculate scale between the buffers and the final upscaled image to prevent roundoff errors.
            correctedScaleX = _defData.width/_buffer1.width;
            correctedScaleY = _defData.height/_buffer1.height;

            // Create reusable objects
            _fullRect = new Rectangle(0, 0, _buffer1.width, _buffer1.height);
            _drawRect = new Rectangle();

            // Create the DisplacementMapFilter and assign it to the source
            _filter = new DisplacementMapFilter(_defData, _origin, BitmapDataChannel.BLUE, BitmapDataChannel.BLUE, strength, strength, "wrap");
            _source.filters = [_filter];

            // Create a frame-based loop to update the ripples
            _source.addEventListener(Event.ENTER_FRAME, handleEnterFrame);

            // Create the filter that causes the ripples to grow.
            // Depending on the colour of its neighbours, the pixel will be turned white
            _expandFilter = new ConvolutionFilter(3, 3, [0.5, 1, 0.5, 1, 0, 1, 0.5, 1, 0.5], 3);

            // Create the colour transformation based on
            _colourTransform = new ColorTransform(1, 1, 1, 1, 128, 128, 128);

            // Create the Matrix object
            _matrix = new Matrix(correctedScaleX, 0, 0, correctedScaleY);

        }

        /**
         * Initiates a ripple at a position of the source DisplayObject.
         *
         * @param x The horizontal coordinate of the ripple origin.
         * @param y The vertical coordinate of the ripple origin.
         * @param size The size of the ripple diameter on first impact.
         * @param alpha The alpha value of the ripple on first impact.
         */
        public function drawRipple(x : int, y : int, size : int, alpha : Number) : void
        {
            var half : int = size >> 1;        // We need half the size of the ripple
            var intensity : int = (alpha*0xff & 0xff)*alpha;    // The colour which will be drawn in the currently active buffer

            // calculate and draw the rectangle, having (x, y) in its centre
            _drawRect.x = (-half+x)*_scaleInv;
            _drawRect.y = (-half+y)*_scaleInv;
            _drawRect.width = _drawRect.height = size*_scaleInv;
            _buffer1.fillRect(_drawRect, intensity);
        }

           /**
            * Returns the actual ripple image.
            */
        public function getRippleImage() : BitmapData
        {
            return _defData;
        }

        /**
         * Removes all memory occupied by this instance. This method must be called before discarding an instance.
         */
        public function destroy() : void
        {
            _source.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
            _buffer1.dispose();
            _buffer2.dispose();
            _defData.dispose();
        }

        // the actual loop where the ripples are animated
        private function handleEnterFrame(event : Event) : void
        {
            // a temporary clone of buffer 2
            var temp : BitmapData = _buffer2.clone();
            // buffer2 will contain an expanded version of buffer1
            _buffer2.applyFilter(_buffer1, _fullRect, _origin, _expandFilter);
            // by substracting buffer2's old image, buffer2 will now be a ring
            _buffer2.draw(temp, null, null, BlendMode.SUBTRACT, null, false);
            // scale up and draw to the final displacement map, and apply it to the filter
            _defData.draw(_buffer2, _matrix, _colourTransform, null, null, true);
            _filter.mapBitmap = _defData;
            _source.filters = [_filter];
            temp.dispose();
            // switch buffers 1 and 2
            switchBuffers();
        }

        // switch buffer 1 and 2, so that
        private function switchBuffers() : void
        {
            var temp : BitmapData;
            temp = _buffer1;
            _buffer1 = _buffer2;
            _buffer2 = temp;
        }
    }
}
Filed under: AIR+FB+AS3, Demo 1 Comment
1305/108

AS3-LightOut

来个LightOut小游戏,至于LightOut是啥,可以看这里:http://en.wikipedia.org/wiki/Lights_Out_%28game%29
如果该页面被和谐,那可以看下@dfdou的简单介绍,LightOut是一个开/关游戏,游戏的目的很简单,在5x5的的方阵里,把全部的图换成亮着的状态就过关了,Demo里是白色方块代表亮起状态。
规则是点击一个方块,在方块4周的4个方块和方块本身的状态会发生改变,是亮起就变成关掉,是关掉就变成亮起~

Demo在这里:

下边来讲下代码部分,比较简单,3个类搞定。

2004/102

AS3-Sokoban推箱子-寻路扩展

恩,是寻路扩展,而不是自动求解~自动求解那个实在过于复杂,不考虑呀么不考虑。
先看demo:

依然是前几天的Sokoban,只不过修改了下地图数据,另外加了个点击寻路功能。
在要去的点上点一下鼠标,就会自动移过去了。
下边来说下具体实现。

1404/1011

AS3-Sokoban推箱子

先是Demo:

方向键控制移动,红色的方块是你~
UI嘛,就不说了,网上偷了点图,就这么放着了,有兴趣的可以弄弄呗。

Source code:https://dl.dropbox.com/u/477487/flash/game/sokoban.rar

PS:如果该地址被和谐,而你又想要源代码,联系我,服务很周到的~

推箱子的实现方法很多,各有各的做法,下边是我的实现方式:
Sokoban.as:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	/**
	 * ...
	 * @author DFdou
	 */
	public class Sokoban extends Sprite {
		private var _lv = 0;
		private var _map:Map;

		public function Sokoban() {
			init();
		}
		private function init() {
			_map = new Map(_lv);
			addChild(_map);

			var role:Role = new Role(stage,_map,_lv);
			addChild(role);
		}

	}
}

文档类要干的事儿就是生成一个map,一个role。

104/101

Flash – Demo41

Demo:

部分Code:
AUIS.as

package org.nwhy.auis {
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.MouseEvent;

	public class AUIS extends Sprite {
		private var itemHolder:Sprite;

		public function AUIS() {
			init();
		}
		private function init() {
			initStage();
			initListeners();
			initItems();
		}
		private function initStage() {
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.frameRate = 55;
		}
		private function initListeners() {
			stage.addEventListener(MouseEvent.MOUSE_DOWN, mClick);
		}
		private function initItems() {
			itemHolder = new Sprite();
			addChild(itemHolder);
			itemHolder.x = 150;
			itemHolder.y = 80;
			ItemFactory.createRandomItems(itemHolder,150);
		}
		private function mClick(e:MouseEvent) {
			var sp:Sprite = new Sprite();
			addChild(sp);
			sp.x = mouseX;
			sp.y = mouseY;
			//生成14个item
			ItemFactory.createClickEffectItems(sp);
		}
	}
}
2903/104

FP10-FileReference.save()

Flash Player10支持的一个API,10以下不支持,就别挣扎了~
Demo:

功能很简单,点击那个不太起眼的Download下载图片。
代码也十分的简单:

import com.adobe.images.JPGEncoder;

btn_download.addEventListener(MouseEvent.MOUSE_DOWN,download);
function download(e:MouseEvent){
	var bit:BitmapData = new BitmapData(505,460);
	bit.draw(bitmap);
	var file:FileReference = new  FileReference();
	var jpg:JPGEncoder = new JPGEncoder(100);
	file.save(jpg.encode(bit),"bitmap.jpg");
}

com.adobe是Adobe出的扩展类包,去下一个吧,挺好用的。
整个过程就是生成一个Bitmap,然后调用FileReference.save()保存到本地呗~

1803/103

AS3-Mapppp~的一个生成方案

最近的一个Android里碰到一个Map的应用,做了下这个东西,这个东西挺简单的,就是根据给出的数组生成一个Map。
Demo出来玩下先:

大小是800*500,想看全景的点这里呗:http://nwhy.org/nwhy/game/MapConvert.swf

整个实现过程很简单,MapConvert.as:

/*
VERSION: 1.0 DATE:2010/03/18
ACTIONSCRIPT VERSION: 3.0
AUTHOR: DFdou
Copyright 2009, http://nwhy.org. All rights reserved.
*/
package{
	import flash.display.Sprite;

	public class MapConvert extends Sprite{
		private var map:Map;
		private var mapID:uint;

		public function MapConvert(){
			mapID = 0;
			map = new Map(mapID);
			addChild(map);
		}
	}
}

文档类干的事灰常简单,传一个mapID生成一个Map,加到显示列表,就完事儿了。
Map.as:

/*
VERSION: 1.0 DATE:2010/03/18
ACTIONSCRIPT VERSION: 3.0
AUTHOR: DFdou
Copyright 2009, http://nwhy.org. All rights reserved.
*/
package{
	import flash.display.Sprite;

	public class Map extends Sprite{
		private var data:Array;

		public function Map(id:uint){
			data = MapData.MAP[id];
			var row:uint = data.length;
			for(var i:uint = 0;i<row;i++){
				var col:uint = data[i].length;
				for(var j:uint = 0;j<col;j++){
					if(data[i][j]!=0){
						var tile:Tile = new Tile();
						tile.gotoAndStop(data[i][j]);
						tile.x = j * 50;
						tile.y = i * 50;
						addChild(tile);
					}
				}
			}
		}
	}
}

Map类也很简单,根据传过来的mapID载入对应的Map数组,然后就生成Tile来填充呗~
最后是示例性数据结构MapData.as:

/*
VERSION: 1.0 DATE:2010/03/18
ACTIONSCRIPT VERSION: 3.0
AUTHOR: DFdou
Copyright 2009, http://nwhy.org. All rights reserved.
*/
package {
	public class MapData {
		public static  const MAP:Array = [
										  [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10],
										   [0,1,0,0,14,0,0,0,0,0,0,0,6,0,0,0],
										   [0,0,1,0,0,0,0,0,5,0,12,0,1,0,0,0],
										   [0,0,0,0,9,0,0,0,0,0,0,0,0,0,3,0],
										   [0,0,5,1,5,5,0,0,0,0,1,0,0,0,3,0],
										   [0,0,0,0,0,0,0,0,0,0,6,4,0,3,0,0],
										   [0,0,5,0,0,4,1,0,0,0,0,9,0,12,0,0],
										   [0,0,0,0,0,0,0,0,0,0,11,0,1,0,0,0],
										   [0,0,0,2,0,0,2,0,0,0,3,10,9,9,0,0],
										   [0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],
										  ];
	}
}
Tagged as: 3 Comments
903/107

Flash-APE物理引擎学习<二>

昨天整理了下代码,新的Demo在这里:

在说具体实现之前,丢个Flash物理引擎在产品展示中的应用:http://www.carlosulloa.com/.
这是一款汽车产品的展示平台,用方向键控制机车移动,点鼠标左键复位汽车初始位置。
不过,这个不是2d物理引擎完成的,而是基于PV3D的,,,,恩,3D物理引擎是在比较难搞……有时间尝试整理下……

下边来说下Demo的具体实现,首先要收下物理引擎,物理引擎是干嘛用的呢?
物理引擎是一个处理物理现象的引擎。

那什么是物理现象呢?
举个例子,一个风筝在天上飞,它会受到风力,阻力,摩擦力,还有重力,绳子的作用力,etc。。。而物理引擎就是帮你处理这些力的一个框架集。
你要做的就是给它个重力,然后都作用在风筝上,至于这些里之间的相互作用,都由引擎来搞定。

下边来代码,先是文档类,也就是主容器了:

package org.nwhy.bubble_bobble{
	import flash.display.*;
	import flash.events.Event;
	import org.cove.ape.*;

	public class BubbleBobble extends Sprite{
		private var bulletHolder:Group;

		public function BubbleBobble(){
			init();
		}
		private function init(){
			initStage();
			initGroups()
		}
		private function initStage(){
			stage.scaleMode = StageScaleMode.NO_SCALE;//设置为不缩放
			//stage.align = StageAlign.TOP_LEFT;
			stage.frameRate = 55;//设置帧频
			stage.addEventListener(Event.ENTER_FRAME, run);
		}
		private function initGroups(){
			//初始化2D物理引擎
			APEngine.init(1/4);
			APEngine.container = this;
			APEngine.addForce(new VectorForce (false,0,1));//加上重力

			//放bullet的容器,bullet就是那个各种颜色的球~
			bulletHolder = new Group(true);
			APEngine.addGroup(bulletHolder);

			//加入墙壁
			var wall:Wall = new Wall();
			APEngine.addGroup(wall);

			//gun,就是下边那个大伯说有点像啥的那个啥……囧一个
			var gunGroup:GunGroup = new GunGroup(stage);
			APEngine.addGroup(gunGroup);

			//设置bullet的碰撞检测内容
			bulletHolder.addCollidableList(new Array(wall,gunGroup));
		}
		private function run(e:Event) {
			APEngine.step();
			APEngine.paint();
		}
		//增加bullet的对外接口
		public function addBullet(bullet:CircleParticle){
			bulletHolder.addParticle(bullet);
		}
	}
}

这里边干的事就是加入各种Group(APE物理引擎里的碰撞单元是Particle,单个或多个Particle组成Group),至于Group里具体是啥Group里自己处理。

1612/092

AS3-StringParser 繁简体火星文转换

先来个Demo:

关于火星文,其实我有很多关于脑残的话要说,不过这里不谈火星文和脑残的关系,只谈前端开发的时候会碰到火星文的问题。
啥么?你说啥时候会碰到啊?
比如脏话过滤的时候,比如是否汉字判断的时候。
这个就要说到火星文的产生,以及编码段,大家自个儿去查wiki去。
别只顾着鄙视90后和火星文的存在,网站是需要兼容的,understand?

2611/091

AS3-Caurina 动画类

今天玩了下Caurina类,和TweenLite的差别并不大,具体哪个好用,对我来说,TweenLite更熟悉点=,=
而老外(尤其是日本人)的Flash破解出来基本都是Caurina来作为Tween类,因为Caurina开源的关系么?
Caurina官方地址如下:http://hosted.zeh.com.br/tweener/docs/en-us/
类包下载地址:http://code.google.com/p/tweener/downloads/list,看好版本再下载哈。
最简单的动画代码如下:

import caurina.transitions.Tweener;
Tweener.addTween(clip_mc,{x:500,time:1,transition:"easeOutBounce"});

让clip_mc的x位置花1s的时间运动到500位置,动画的ease为easeOutBounce。熟悉TweenLite的应该很快就可以熟悉Caurina了。至于addTween的详细参数,,自己看文档去~
下边来个结合Timer的Demo,来自flepstudio.org

2411/090

AS3-SharedObject Flash的Cookie

该从何讲起呢,,先说浏览器的Cookie吧,可以方便的记录一些东西,但是Flash就比较麻烦了,如果要操作Cookie,还得借助其他语言,js,php,asp?着实有点让人不爽,不过Adobe给了个SharedObject给大家玩,借助这个东西保存客户端的信息就比较easy了,来,咱来看个Demo:

Demo代码:

import org.nwhy.utils.*;
init();
function init() {
	var ckie:FlashCookie=new FlashCookie("nwhy");
	if (ckie.data.txt) {
		txt.text=ckie.data.txt;
	} else {
		txt.text="暂无数据";
	}
	btn.addEventListener(MouseEvent.CLICK,saveCookie);
	function saveCookie(_e:MouseEvent) {
		ckie.data.txt=txt.text;
		ckie.flush();
	}
	btnClear.addEventListener(MouseEvent.CLICK,clearCookie);
	function clearCookie(_e:MouseEvent) {
		ckie.clear();
	}
}

是不是跟Cookie一样顺手?

2311/097

AS3-Captcha验证码类

忽然想做个Flash版的验证码,于是就做了,先来看下Demo:

哈哈,是不是觉得最后那个验证码很变态=。=

2011/092

AS3-Effect explode 图片爆炸效果

这个需求是昨天碰到的,怎么说呢,怪怪的,主要是想不出可以模拟爆炸效果的公式。
先来看Demo:

1611/099

Air-fWeather Google Weather Api使用例子

需要Flash Player9+,如果你看到这段文字,请点击下边的图片链接更新您的Flash Player,或者直接下载Air文件进行安装。
get_flash_player

AIR程序下载地址(需要先安装AIR运行时):http://nwhy.org/nwhy/fDEV/fWeather.air.
fWeather
不知道为什么,Google Weather Api的说明文档一直没有找到,难道现在连Lab状态都不是?
这次是用Flash CS4做的AIR程序,发布的时候发现Flash在生成xml配置文件的时候存在一点问题啊……

1211/090

AS3-视频拍照功能

Demo:


下载地址:http://dl.dropbox.com/u/477487/flash/as3/AvatarEdit.rar,呵呵,老规矩,豆腐不保证这个链接的永久有效性哈哈。

Page 1 of 612345...Last »