mardi 29 septembre 2015

How drag a Sprite smoothly on-screen in actionscript

First of all, my question is basically the same as this one:

How to drag an image to move it smoothly on screen, with ActionScript?

I want my dragged Sprites to keep up with the mouse on-screen, smoothly, without lagging behind.

And I notice that in the old ActionScript 3 Cookbook from way-back-when that they used a similar solution for their DraggableSprite as was used in the above link. Namely, use the stage instance to listen for the MouseMove event and then read from the event.stageX and stageY properties.

I've done that.

But my Sprite still doesn't stay locked with the mouse cursor. It lags behind. I feel like I must be missing something. However, if the solution posted above (ie listen for stage's MouseMove and use event.stageX/Y) is still current and the problem I'm describing should not be occurring, please also let me know. Even though it's not supposed to work, I've tried event.updateAfterEvent() and it also doesn't seem to have any positive effect.

Any help or advice would be greatly appreciated.

Here's a simple example of how I've written the handlers. It should work as-is if pasted into a new project.

I should also add that I'm compiling this as a desktop application using Adobe AIR. Would the run time be a factor???

package {
  import flash.display.Sprite;

  [SWF(width="1280", height="720", frameRate="30")]
  public class test_drag extends Sprite {

    private var testDragSprite:TestDragSprite;

    public function test_drag() {

      graphics.drawRect(0, 0, 1280, 720);

      testDragSprite = new TestDragSprite();

      testDragSprite.addEventListener(MouseEvent.MOUSE_DOWN, testDragSprite_mouseHandler);
      testDragSprite.addEventListener(MouseEvent.MOUSE_UP, testDragSprite_mouseHandler);

    private function testDragSprite_mouseHandler(e:MouseEvent):void {
      switch (e.type) {
        case MouseEvent.MOUSE_DOWN: {
          stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
        case MouseEvent.MOUSE_UP: {
          stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

    private function mouseMoveHandler(e:MouseEvent):void {
      //-20 to keep the sprite centered on the mouse
      testDragSprite.x = e.stageX - 20;
      testDragSprite.y = e.stageY - 20;
      //e.updateAfterEvent(); //strange effect, but doesn't solve the problem.
import flash.display.Sprite;
internal class TestDragSprite extends Sprite {
  public function TestDragSprite() {
    graphics.lineStyle(1, 0xDDDDDD);
    graphics.drawRoundRect(0, 0, 40, 40, 12);

Aucun commentaire:

Enregistrer un commentaire