在AS3物理引擎APE试用一文中,我简单记录了关于APE的基本调用,并实现了在重力作用环境下,一个自由落体的碰撞过程。现在我们把代码来改进一下,修改为一个横版的动作游戏场景(虽然目前它还算不上游戏,呵呵)
首先,我定义了6个固定的高度为10的矩形物件。作为地图场景,而规定了一个宽高均为20的正方形物件来表示玩家。通过响应键盘事件来达到控制玩家动作的效果。摩擦系数设置为0.1
效果如下(左右键,空格):
参考代码如下:
// D5Power Studio
// Author:Benmouse
import org.cove.ape.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
// 定义地图
public var mapblock0:RectangleParticle;
public var mapblock1:RectangleParticle;
public var mapblock2:RectangleParticle;
public var mapblock3:RectangleParticle;
public var mapblock4:RectangleParticle;
public var mapblock5:RectangleParticle;
public var mapblock6:RectangleParticle;
// 定义玩家
public var map:Group;
public var myplayer:RectangleParticle;
public var player:Group;
// 代替setInterval,目前没有使用
public var myTimer:Timer;
public var myFriction:Number=0.1;
[SWF(width="650", height="350", backgroundColor="#334433")]
public function init():void
{
// 初始化地图
mapblock0=new RectangleParticle(0,400,600,10,0,true);
mapblock1=new RectangleParticle(0,100,100,10,0,true);
mapblock2=new RectangleParticle(160,100,120,10,0,true);
mapblock3=new RectangleParticle(300,100,100,10,0,true);
mapblock4=new RectangleParticle(90,200,90,10,0,true);
mapblock5=new RectangleParticle(200,200,60,10,0,true);
mapblock6=new RectangleParticle(150,300,200,10,0,true);
// 设置摩擦系数
mapblock0.friction = myFriction;
mapblock1.friction = myFriction;
mapblock2.friction = myFriction;
mapblock3.friction = myFriction;
mapblock4.friction = myFriction;
mapblock5.friction = myFriction;
map=new Group();
// 初始化玩家
myplayer=new RectangleParticle(0,0,20,20,0);
myplayer.friction = myFriction;
player=new Group();
// 向GROUP中增加对象
map.addParticle(mapblock0);
map.addParticle(mapblock1);
map.addParticle(mapblock2);
map.addParticle(mapblock3);
map.addParticle(mapblock4);
map.addParticle(mapblock5);
map.addParticle(mapblock6);
player.addParticle(myplayer);
stage.frameRate = 55;
APEngine.init(0.25);
APEngine.container = stage;
APEngine.addGroup(map);
APEngine.addGroup(player);
APEngine.addForce(new Vector(0, 9.8));
map.addCollidable(player);
// 设置键盘侦听
stage.addEventListener(KeyboardEvent.KEY_DOWN,myCtrl);
stage.addEventListener(KeyboardEvent.KEY_UP,myStopCtrl);
stage.addEventListener(Event.ENTER_FRAME,run)
}
public function run(e:Event):void
{
APEngine.step();
APEngine.paint();
}
public function myCtrl(e:KeyboardEvent):void
{
// 根据按键不同触发相关事件
tester.text=e.keyCode.toString();
var speed:int=2;
switch(e.keyCode)
{
case 39:
myplayer.velocity=new Vector(speed,0);
break;
case 37:
myplayer.velocity=new Vector(speed*-1,0);
break;
case 32:
// 由于跳跃是一瞬间的事情,所以采用了增加反重力方向的外力
myplayer.addForce(new Vector(0,speed*80*-1));
break;
}
}
public function myStopCtrl(e:KeyboardEvent):void
{
}
public function clearVelocity():void
{
}
目前存在的问题:地图未规范化,创建地图非常复杂,应该采用数组的形式进行保存;人物会在空中凭空借力(轻功太好了,呵呵)
本文来源于 冰山上的播客 http://xinsync.xju.edu.cn , 原文地址:http://xinsync.xju.edu.cn/index.php/archives/789