2011-12-15 70 views
1

我想创建一个玩家对象的边界,用箭头键控制,在我的游戏中使用主舞台的高度和宽度。例如,一个测试点位于玩家对象的边界框的顶部边缘,以便当玩家对象的头部接触到舞台的顶部边缘时,玩家不能再向北移动。玩家对象通过使用Flash舞台编辑器手动实例化到舞台的中心,因此它将在程序启动之前从中心开始。使用hitTestPoint()与舞台对象创建对象的边界

问题是,在程序开始时,我不能再用箭头键向上或向下移动播放器对象,但我仍然可以左右移动它。其目的是让玩家向北移动,直到玩家对象的头部接触主舞台的顶部边缘。下面的代码:

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

回答

2

使用设置为true的形状标志的阶段目标是将产生错误:你测试,如有呈现在舞台上的实际像素的撞击点(这可能会返回false,除非在可见舞台区域之外的物体恰好在指定的位置)。

当然,您可以将其设置为false,然后再试一次(这样做会更好,但仍然会出现问题,即您正在测试舞台上呈现的所有内容的边界框,而不是实际舞台区域),但我可能会建议一种不同的方法?

这是更有效,特别是因为你的精灵可能比舞台小得多,测试玩家的边框对舞台的界限:

function onEnterFrame (ev:Event) : void { 
    player.x += vx; 
    player.y += vy; 

    var playerBounds:Rectangle = player.getBounds(stage); 
    if (playerBounds.left < 0 || playerBounds.right > stage.stageWidth) player.x -= vx; 
    if (playerBounds.top < 0 || playerBounds.bottom > stage.stageHeight) player.y -= vy; 
} 

玩家必须位于舞台可见区域内当然,在启动时,您可能必须将焦点放在舞台上以确保捕获键盘事件。

+0

我已经使用其他方法成功,但我很好奇'hitTestPoint`如何工作。我已经将hitTestPoint的第三个参数设置为false。玩家对象现在可以向北移动,而不是停在舞台的边缘,而是被与玩家对象高度相同的不可见屏障阻挡。在“hitTestPoint”的第二个参数中,我将`player.height`分为4,而玩家对象在向北行进时会离开舞台边界。 – user701510 2011-12-15 08:26:39