玩rpg游戏的时候,会看到角色始终在屏幕中间移动,感觉是地图在动,人物位置不动,这是如何来实现的呢?
看了下面这个简单例子你便知道其中的道理,原理是利用DisplayObject的ScrollRect:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package { import flash.display.Loader; import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Rectangle; import flash.net.URLRequest; /** * 滚动地图的例子: * 将window.x和window.y放在EnterFrame中,实时修改为角色走动的坐标即可实现地图平滑滚动 * 这里简单用鼠标点击坐标作为角色的位置 * jianzi 2010.7.8 */ public class Main extends Sprite { //地图尺寸 private static const mapWidth:int = 2762; private static const mapHeight:int = 1558; //地图入口坐标 private static const enterX:int = 1000; private static const enterY:int = 1200; //滚动区域 private var window:Rectangle; //地图层 private var scene:Sprite public function Main() { //地图层 scene = new Sprite(); scene.graphics.beginFill(Math.random() * 0xffffff); scene.graphics.drawRect(0,0,mapWidth,mapHeight); scene.graphics.endFill(); //加载地图 var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete); loader.load(new URLRequest("map.jpg")); scene.addChild(loader); addChild(scene); //滚动区域,设置为stage大小,定位地图在入口点(enterX,enterY) window = new Rectangle(); window.x = enterX - stage.stageWidth/2; window.y = enterY - stage.stageHeight/2; window.width = stage.stageWidth; window.height = stage.stageHeight; this.scrollRect = window; this.addEventListener(MouseEvent.CLICK,onClick); } private function onComplete(e:Event):void { //...................... } private function onClick(e:MouseEvent):void { var posX:Number = int(mouseX) - stage.stageWidth/2; var posY:Number = int(mouseY) - stage.stageWidth/2; if (posX < 0) posX = 0; else if ((posX+stage.stageWidth) > mapWidth) posX = mapWidth - stage.stageWidth; if (posY < 0) posY = 0; else if ((posY+stage.stageHeight) > mapHeight) posY = mapHeight - stage.stageHeight; window.x = posX; window.y = posY; trace(window.x,window.y); this.scrollRect = window; } } }
|
全文完。