Java滚动地图层的方法



Java滚动地图层的方法。玩rpg游戏的时候,会看到角色始终在屏幕中间移动,感觉是地图在动,人物位置不动,这是如何来实现的呢?

看了下面这个例子你便知道其中的道理,原理是利用DisplayObject的ScrollRect:

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;
}

}
}