2013-02-03 70 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; 
}