【转】游戏人物走动与场景自动滚动(滚屏)

测试要求:在库中建立人物和场景地图(大于一屏宽度) s h

 

代码类如下:

/* 这是一个用于游戏场景滚屏的代码,左右二个方向

See the book or site for more information
*/

package {
import flash.display.*;
import flash.events.*;
import flash.utils.getTimer;

public class mcMove extends MovieClip {
private var moveLeft:Boolean=false;
private var moveRight:Boolean=false;
private var edgeDistance:Number=250;//主人公自由运动区域(背景图片不滚屏气凝神,左右二侧的距离)
private var speed:Number=2;
private var scene:MovieClip;//场景背景影片剪辑
private var hero:MovieClip; //场景背景影片剪辑内部的主人公对象

//
public function mcMove():void{
setMove(main,main.mc);
}


private function setMove(s:MovieClip,h:MovieClip) {
if(s!=null&&h!=null){
scene=s;//s和h为为中的人物和场景影片剪辑对象
hero=h;
initListener();
trace("启动")
}
}


private function initListener():void{

this.addEventListener(Event.ENTER_FRAME,moveLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);

}


// note key presses, set hero properties
private function keyDownFunction(event:KeyboardEvent) {


if (event.keyCode == 37) {
moveLeft = true;
} else if (event.keyCode == 39) {
moveRight = true;
}
}
private function keyUpFunction(event:KeyboardEvent) {
switch (event.keyCode) {
case 37 :
moveLeft = false;
break;
case 39 :
moveRight = false;
break;
}
}

private function moveLoop(event:Event):void{
if(moveLeft==true){
if(hero.x-speed<hero.width/2){
hero.x=scene.mc.width/2;
}else{
scene.mc.x-=speed;
}
}

if(moveRight==true){
if(hero.x+speed>scene.width-hero.width/2){
hero.x=scene.width-hero.width/2;
}else{
hero.x+=speed;
}
}

scrollWithHero();

}

//更新整个场景联合元件的坐标
private function scrollWithHero() {
var stagePosition:Number = scene.x+scene.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;

if (stagePosition > rightEdge) {
scene.x -= (stagePosition-rightEdge);
if (scene.x < -(scene.width-stage.stageWidth)) {
scene.x = -(scene.width-stage.stageWidth);
}
}
if (stagePosition < leftEdge) {
scene.x += (leftEdge-stagePosition);
if (scene.x > 0) {
scene.x = 0;
}
}

}

}
}



posted @ 2012-03-31 11:55  tinytiny  阅读(552)  评论(0编辑  收藏  举报