我试图在我的游戏中使用主舞台的高度和宽度为玩家对象创建一个边界,用箭头键控制。例如,一个测试点位于玩家对象的边界框的顶部边缘,这样当玩家对象的头部接触到舞台的顶部边缘时,玩家就不能再向北移动了。播放器对象通过使用 Flash 舞台编辑器手动实例化到舞台中心,因此它将在程序启动之前从中心开始。
问题是在程序开始时,我不能再用箭头键上下移动播放器对象,但我仍然可以左右移动它。目的是让玩家向北移动,直到玩家对象的头部接触到主舞台的顶部边缘。这是代码:
package
{
public class Main_Playground extends MovieClip
{
var vx:int;
var vy:int;
public function Main_Playground()
{
init();
}
function init():void
{
//initialize variables
vx = 0;
vy = 0;
//Add event listeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
}
else if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
}
else if (event.keyCode == Keyboard.UP)
{
vy = -5;
}
else if (event.keyCode == Keyboard.DOWN)
{
vy = 5;
}
}
function onKeyUp(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
}
else if (event.keyCode == Keyboard.DOWN || event.keyCode == Keyboard.UP)
{
vy = 0;
}
}
function onEnterFrame(event:Event):void
{
//Move the player
player.x += vx;
player.y += vy;
//determine top boundary
if (! stage.hitTestPoint(player.x, (player.y-(player.height/2)), true ) ){
player.y -= vy;
}
}
}
}