使用Actionscript 3.0拖动,就像在RTS游戏中移动相机一样

时间:2013-02-03 19:23:50

标签: actionscript-3 flash draggable

我正在尝试使用Flash构建RTS游戏并进行一些基本测试。我遇到this site教我拖动物体。我修改了代码以模拟在点击它的同时移动游戏的游戏世界。中心圆是摄像机的焦点/中心。矩形板代表游戏世界。

我尝试更改功能boardMove,根据mouseX和mouseY单击并移动。但每次点击时,mouseX和mouseY都会成为电路板的中心,这不是我想要的。我想让它相对到鼠标位置,但我只能让电路板闪烁,或者左上角移动。

任何建议都将不胜感激。

// Part 1 -- Setting up the objects

var board:Sprite = new Sprite();
var myPoint:Sprite = new Sprite();
var stageWidth = 550;
var stageHeight = 400;
var boardWidth = 400;
var boardHeight = 300;
var pointWidth = 10;

this.addChild(board);
this.addChild(myPoint);

board.graphics.lineStyle(1,0);
board.graphics.beginFill(0xCCCCCC);
board.graphics.drawRect(0,0,boardWidth,boardHeight);
board.graphics.endFill();
board.x = (stageWidth - boardWidth) / 2;
board.y = (stageHeight - boardHeight) / 2;

myPoint.graphics.lineStyle(1,0);
myPoint.graphics.beginFill(0x0000FF,0.7);
myPoint.graphics.drawCircle(0,0,pointWidth);
myPoint.graphics.endFill();
myPoint.x = (stageWidth - pointWidth) / 2;
myPoint.y = (stageHeight - pointWidth) / 2;


// Part 2 -- Add drag-and-drop functionality - Better Attempt

stage.addEventListener(MouseEvent.MOUSE_DOWN, startMove);

function startMove(evt:MouseEvent):void {
    stage.addEventListener(MouseEvent.MOUSE_MOVE, boardMove);
}

// Revised definition of pointMove in Part II of our script

function boardMove(e:MouseEvent):void {
    board.x = checkEdgeX(board.mouseX);
    board.y = checkEdgeY(board.mouseY);
    e.updateAfterEvent();
}

stage.addEventListener(MouseEvent.MOUSE_UP, stopMove);

function stopMove(e:MouseEvent):void {
    stage.removeEventListener(MouseEvent.MOUSE_MOVE, boardMove);
}


// Part III -- Check for boundaries

function checkEdgeX(inX:Number):Number {
    var x = stageWidth / 2 - boardWidth;
    if (inX < x) {
        return x;
    }

    x = stageWidth / 2;
    if (inX > x) {
        return x;
    }

    return inX;
}

function checkEdgeY(inY:Number):Number {
    var y = stageHeight / 2 - boardHeight;
    if (inY < y) {
        return y;
    }

    y = stageHeight / 2;
    if (inY > y) {
        return y;
    }

    return inY;
}

1 个答案:

答案 0 :(得分:1)

一种选择是确定鼠标的相对运动并相应地移动板;类似的东西:

private Point lastPosition;

function startMove(...) {
    lastPosition = null;
    ...
}

function boardMove(e:MouseEvent):void {
    Point position = new Point(stageX, stageY);
    if (lastPosition != null) {
        Point delta = position.subtract(lastPosition);
        board.x += delta.x; // NOTE: also try -= instead of +=
        board.y += delta.y; // NOTE: also try -= instead of +=
        e.updateAfterEvent();
    }
    lastPosition = position;
}