在大部分需要用户点击的游戏中,坐标的转换是一种必须熟练掌握的方法。
首先在一个700x700的舞台中创建2个方块,红色的大方块A是600x600,位于(50,50),绿色的小方块B是300x300。A是B的父容器,B相对于舞台位于(200,200)。
接下来做一系列的测试来阐明这2个方法是如何运作的。
假设我们点B方块的中心点,即全局(350,350),A(300,300),B(150,150),看看结果分别会怎么样:
private function onClickHandler(e:MouseEvent):void
{
e.stopPropagation();
var stagePoint:Point = new Point(stage.mouseX, stage.mouseY);
trace(stagePoint.x); //350
trace(stagePoint.y); //350
trace(stage.globalToLocal(stagePoint).x); //350
trace(stage.globalToLocal(stagePoint).y); //350
trace(smallShape.globalToLocal(stagePoint).x); //150
trace(smallShape.globalToLocal(stagePoint).y); //150
trace(bigShape.globalToLocal(stagePoint).x); //300
trace(bigShape.globalToLocal(stagePoint).y); //300
var localPoint:Point = new Point(e.localX, e.localY);
trace(localPoint.x); //150
trace(localPoint.y); //150
trace(stage.localToGlobal(localPoint).x); //150
trace(stage.localToGlobal(localPoint).y); //150
trace(smallShape.localToGlobal(localPoint).x); //350
trace(smallShape.localToGlobal(localPoint).y); //350
trace(bigShape.localToGlobal(localPoint).x); //200
trace(bigShape.localToGlobal(localPoint).y); //200
}
通过测试结果可见,globalToLocal方法把同一个全局坐标(350,350)由谁来调用就是转换给谁的local坐标。localToGlobal方法略微复杂一点,由谁来调用localToGlobal就相当于在localPoint(150,150)的基础上加上调用者在舞台的坐标。
理解了这2个方法的运作方式后,假设我们点击B方块某位置要将其转换为A方块的坐标就很简单了:
private function onClickHandler(e:MouseEvent):void
{
var localPoint:Point = new Point(e.localX, e.localY);
var stagePoint:Point = smallShape.localToGlobal(localPoint);//因为点击的位置在B方块内,所以由B调用
localPoint = bigShape.globalToLocal(stagePoint);//点击处在A方块的坐标
}