设置MovieClip(AS3)的边界限制

时间:2010-09-22 01:47:50

标签: flash

我有一个可以向上,向下,向左和向右移动的MovieClip。如果MovieClip碰到一堵墙,那么MC会弹跳,不应该越过墙 - 但如果你继续按下你的上,下,左或右键,并且不要放手 - MovieClip将会过去墙。我正试图找出一种方法,阻止它发生。 link of movement

    // function hitWall --------------------------------------------------------------
    function hitWall(event:Event):void {
        if (box.hitTestObject(wall)) {
                box.y+=6;
            } else if (box.hitTestObject(wall2)) {
                box.y-=6;

            } else if (box.hitTestObject(wall3)) { 
                box.x+=6;

            } else if (box.hitTestObject(wall4)) {
                box.x-=6;
            }

    }

    // function keyDownEvent ------------------------------------------------------------
     function keyDownEvent(event:KeyboardEvent):void {
         switch (event.keyCode) {
            case Keyboard.UP:
               keyUpward = true;
               keyDownward = false;
               break;

            case Keyboard.DOWN:
               keyDownward = true;
               keyUpward = false;
               break;

            case Keyboard.LEFT:
               keyLeft = true;
               keyRight = false;
               break;

            case Keyboard.RIGHT:
               keyRight = true;
               keyLeft = false;
               break;
         }
      }

    // function keyUpEvent ------------------------------------------------------------
     function keyUpEvent(event:KeyboardEvent):void {
         switch (event.keyCode) {

            case Keyboard.UP:
               keyUpward = false;
               break;

            case Keyboard.DOWN:
               keyDownward = false;
               break;

            case Keyboard.LEFT:
               keyLeft = false;
               break;

            case Keyboard.RIGHT:
               keyRight = false;
               break;
         }
      }

    // function frameloop ------------------------------------------------------------
     function frameloop(event:Event):void {

         if (keyUpward) {
            forwardMove -=2;
         }
         if (keyDownward) {
            forwardMove += 2;
         }
         if (keyLeft) {
            sideMove -= 2;
         }
         if (keyRight) {
            sideMove += 2;
         }

         forwardMove +=(0-forwardMove)/inertia;
         sideMove +=(0-sideMove)/inertia;

         box.y+=forwardMove;
         box.x+=sideMove;

      } 

2 个答案:

答案 0 :(得分:2)

尝试使用enterframe事件侦听MovieClip的位置,当MovieClip超出范围时,您可以删除键盘事件侦听器或触发相反的键盘事件并使MovieClip以相反的方向反弹

请注意,它可能与您的hitWall()方法冲突,因此您可能最终不得不使用一个解决方案而不是另一个

答案 1 :(得分:0)

基本上,每次移动物体时,都必须测试它是否与墙壁碰撞。如果是,那么你必须将它的位置设置在“安全”区域内。您可以在frameloop的底部进行这些测试。