【问题标题】:how to create up/down movement of sprite with as3 with a mouse如何用 as3 用鼠标创建精灵的向上/向下移动
【发布时间】:2011-01-26 08:21:32
【问题描述】:

我只需要在鼠标移动时垂直移动精灵。如何用 as3 实现?

谢谢

【问题讨论】:

    标签: apache-flex actionscript-3 mouseevent movieclip


    【解决方案1】:

    Flash 版本

    var s:Sprite = new Sprite();
    s.x = 20;
    s.graphics.beginFill(0xFF0000);
    s.graphics.drawRect(0,0,20,20);
    addChild(s);
    
    stage.addEventListener(MouseEvent.MOUSE_MOVE,moveSprite);
    
    function moveSprite(e:MouseEvent):void
    {
        s.y = e.localY;
    }
    

    弹性版

    <mx:Canvas width="100" height="100">
                <mx:mouseMove>
                        <![CDATA[
                            s.y = event.localY;
                        ]]>
                    </mx:mouseMove>
                <mx:Canvas id="s" backgroundColor="#ff0000" width="20" height="20"/>
            </mx:Canvas>
    

    您可以粘贴其中的每一个,并按照您说的做。它将创建一个与鼠标垂直但水平固定的 20x20 红色框。您的鼠标必须在包含的 Canvas 内的 flex 版本。

    【讨论】:

      【解决方案2】:
      addEventListener(MouseEvent.CLICK, clickHandler);
      function clickHandler(e:MouseEvent):void{
          mySprite.y += amount;
      }
      

      【讨论】:

      • 对不起,我问的是鼠标点击,而我实际上需要鼠标移动。点击不跟踪鼠标移动。
      【解决方案3】:

      好的,拖动有点复杂。您需要为拖动的边界定义一个矩形。如果您只想沿一个轴拖动,则使矩形的宽度为 0。在此示例中,我将滚动量和向下限制为您可以在下面更改的不同数字。

      import flash.events.MouseEvent;
      import flash.geom.Rectangle;
      
      mySprite.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
      
      function mouseDownHandler(event:MouseEvent):void{
          stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
          var scrollUpAmount:int = 10;
          var scrollDownAmount:int = 200;
          var boundsRect:Rectangle = new Rectangle(mySprite.x,mySprite.y-scrollUpAmount,0,mySprite.y+scrollDownAmount);
          mySprite.startDrag(false, boundsRect);
      }
      
      function mouseUpHandler(event:MouseEvent):void{
          stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
          mySprite.stopDrag();
      }
      

      【讨论】:

      • 这个例子仅限于垂直拖动,正如我上面解释的那样。如果您只想沿一个轴(例如垂直)拖动,则使边界矩形的宽度为 0。
      猜你喜欢
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多