2013-02-03 69 views
0

我想用Flash構建RTS遊戲並進行一些基本測試。我碰到教我拖動物體的this site。我修改了代碼來模擬移動遊戲的遊戲世界,同時點擊它。中心圓是相機的焦點/中心。矩形板代表遊戲世界。拖動Actionscript 3.0,就像在RTS遊戲中移動攝像機

我試圖改變功能boardMove來點擊並移動根據mouseX和mouseY。但每次點擊時,鼠標X和鼠標Y都會成爲棋盤的中心,這不是我想要的。我想讓它相對鼠標位置,但我只能讓板閃爍,或與其左上角移動。

任何建議,將不勝感激。

// 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; 
} 
+0

看一看的startDrag/stopDrag - 它大部分的工作適合你:http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/ Sprite.html#的startDrag() – 2013-02-03 22:31:55

回答

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